0

I need some help with my code

I wrote a code in C for a program that calculates the largest digit of a number. The problem is that it works for positive numbers, but not for negative ones. What should I do to make it work for both? int main() { int a; scanf("%i", &a); int b=0; while (a) { if (a%10>b) b=a%10; a=a/10; } printf("The largest digit is %i", b); return 0; }

9th Mar 2020, 3:19 PM
Elena Eremia
Elena Eremia - avatar
5 Risposte
+ 2
Import stdlib.h and use the abs() method
9th Mar 2020, 3:31 PM
Jnn
Jnn - avatar
+ 1
Instead of your while loop you can also do: a = abs(a); while(a >= 10){ a /=10; }
9th Mar 2020, 3:35 PM
Jnn
Jnn - avatar
+ 1
Thanks for your advices! It finally worked! :))
9th Mar 2020, 3:55 PM
Elena Eremia
Elena Eremia - avatar
0
You need to check input for <a>, and switch it to positive when and if input number is a negative number. Your approach may not work as expected when input number is negative number. If <a> is less than zero Change <a> to positive number
9th Mar 2020, 3:35 PM
Ipang
11th Mar 2020, 11:29 AM
Yash Kumar
Yash Kumar - avatar