c - program stuck on first printline of the program -
i'm following introductory tutorial c programming. told me write simple program converts degree celsius fahrenheit.
i wrote code shown in video prints first line , gets stuck.
i don't understand what's wrong program:
#include <stdio.h> //program convert celsius fahrenheit int main() { int c; int f; printf("enter temperature in celsius:"); scanf("%d\n", &c); f=9*c/5 + 32; printf("the temperature in fahrenheit is: %d\n",f); return 0; }
i have started using ubuntu , using code block building program gcc compiler.
please thank you;
the problem lies in line of code:
scanf("%d\n", &c);
the escape sequence '\n' not behave think in context: it's not telling scanf() expect input x number in form x\n '\n' linefeed interpreted pattern must matched since scanf() doesn't expand escape sequences.
other characters in template string not part of conversion specifications must match characters in input stream exactly; if not case, matching failure occurs.
so, if enter 10\n input (where \n actual characters , not linefeed), program works.
since not behaviour looking for, can solve problem removing \n template string you're using call scanf().
in case, scanf() default ignores whitespace (such '\n') unless you're using %c or %[ conversion specifiers, there's no need try handle it.
on side note, there's mistake in line
f=9*c/5 + 32;
the correct conversion formula is
f=(9/5) * c + 32;
while doing computer arithmetic order of operations affects final result. (anyway, in case, it's better use floats limit precision loss)
Comments
Post a Comment