Kahl Kahl - 3 months ago 7
C Question

Unlogical output of C code

I wrote some lines of following code.

#include "stdio.h"

int main(){
float t,res;
char c;
scanf("%f",&t);
getchar();
scanf("%s",&c);
if (c=='R') res = 4/5 * t;
else if (c=='F') res = (9/5 * t) + 32;
else if (c=='K') res = t + 273;
printf("%.2f",&res);
return 0;
}


I have no idea why the output shown 0.00 when I give t = 25 and c = 'R'. The console looks like this.

25
R
0.00


Would any body give me an explanation?

Answer
  • scanf("%s",&c); has a big chance to cause out-of-range access, which invokes undefined behavior. Use scanf("%c",&c); (%c instead of %s) to read only one character.
  • printf("%.2f",&res); will invoke undefined behavior by passing data having wrong type to printf(). Use printf("%.2f",res); (without &) to print data having type double (or float, which will automatically converted to double in variable-length arguments)
  • The expressions res = 4/5 * t and res = (9/5 * t) + 32 may not do what you want because 4/5 and 9/5 are integer divisions, in which remainders are truncated. Try using res = 4.f/5 * t and res = (9.f/5 * t) + 32
  • You should check whether scanf()s are successful and the data read is valid in order not to invoke undefined behavior by using values of uninitialized variables having automatic-storage duration, which are indeterminate.