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; }
5 Risposte
+ 2
Import stdlib.h and use the abs() method
+ 1
Instead of your while loop you can also do:
a = abs(a);
while(a >= 10){
a /=10;
}
+ 1
Thanks for your advices! It finally worked! :))
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