1

I was writing a code to convert celsius into fahrenheit putting .2f% in input but it not working:-

#include <stdio.h>
int main()
{
    float celcius, fahrenheit;
    printf("Enter the Temperature in Celsius \n");
    scanf("%.2f", &celcius);
    printf("Temperature in Fahrenheit is %.2f",celcius * 9/5+32);
    return 0;
}

but after I removed the .2f% from input, it starts working. What's the problem there?

HAILEX
  • 33
  • 5
  • 3
    Although `scanf()` and `print()` have some similarities, they are quite different functions, and neither the formats specifiers or their modifiers are the same. Never make assumptions about what one function will do based on the other. – Weather Vane Jan 14 '22 at 09:54
  • 4
    Aside: your expression `celcius * 9/5` luckily does as you want because the computation is `(celcius * 9) / 5` , but the spacing suggests that you assume it will be `celcius * (9/5)`. Obviously the spacing itself doesn't affect it, but please be aware that `9/5` is `1` not `1.8` – Weather Vane Jan 14 '22 at 09:58
  • HAILEX, if input was `"25.125\n"`, what value would you want in `celcius`? – chux - Reinstate Monica Jan 14 '22 at 13:56
  • BTW, `float celcius` is usually is spelled [Celsius](https://en.wikipedia.org/wiki/Celsius). – chux - Reinstate Monica Jan 14 '22 at 13:56
  • @WeatherVane Thank you for insight, but even if it got multiplied first with 9 it wouldn't even make a difference that's why i didn't bother to put it up there. And for the 9/5 part, i already wrote it 9.0/5 to make it float but removed it afterwards as i thought maybe it was giving the wrong answer but luckily it didn't, but still it is technically wrong! – HAILEX Jan 17 '22 at 16:36
  • @chux-ReinstateMonica really ?? I didn't know that. But how will it work? – HAILEX Jan 17 '22 at 16:38
  • @HAILEX There are numerous way to make it work. It depends on the coding goals. So rather than discuss the multitudes of ways, please provide info and details of the goals given various inputs like `25.125, 123, 12.3, 12.30, abc, 0.115, -0.0, -300, 1.99999`, etc. What value should be saved, what text printed? – chux - Reinstate Monica Jan 17 '22 at 16:45

1 Answers1

1

scanf() is not specified to read text up to a limited precision.

scanf("%.2f", &celcius); is an invalid specifier so the result is undefined behavior.

Code can use scanf("%10f", &celcius); to read up to 10 characters (after consuming optional leading whitespace), but that does not really meet OP's goal.

Tip: check the return value of scanf("%.2f", &celcius);.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256