使用gcc编译错误:warning:format指定类型’int *’但参数的类型为’double *’

这是我在C的第一个程序,请温柔的家伙们。

我试图让用户输入温度之间的转换,并使用开关盒来计算转换后的温度。 尝试使用Mac上的gcc编译时,我的以下程序会抛出这样的错误:

convertTemp.c:17:20: warning: format specifies type 'int *' but the argument has type 'double *' [-Wformat] scanf ("%d", &Celcius); ~~ ^~~~~~~~ %lf convertTemp.c:21:72: warning: format specifies type 'int' but the argument has type 'double' [-Wformat] printf ("The converted temperature of %d in Fahreight is: %d\n", Celcius, Fahr); ~~ ^~~~~~~ %f convertTemp.c:21:81: warning: format specifies type 'int' but the argument has type 'double' [-Wformat] printf ("The converted temperature of %d in Fahreight is: %d\n", Celcius, Fahr); ~~ ^~~~ %f convertTemp.c:25:20: warning: format specifies type 'int *' but the argument has type 'double *' [-Wformat] scanf ("%d", &Fahr); ~~ ^~~~~ %lf convertTemp.c:29:70: warning: format specifies type 'int' but the argument has type 'double' [-Wformat] printf ("The converted temperature of %d in Celcius is: %d\n", Fahr, Celcius); ~~ ^~~~ %f convertTemp.c:29:76: warning: format specifies type 'int' but the argument has type 'double' [-Wformat] printf ("The converted temperature of %d in Celcius is: %d\n", Fahr, Celcius); ~~ ^~~~~~~ %f 6 warnings generated. 

码:

 #include  int main (void) { int choice; double Celcius, Fahr; printf ("Do you want to convert from C to F (1) or from F to C(2))?"); scanf ("%i", &choice); switch(choice) { case 1: printf ("Please type the temp in Celcius"); scanf ("%d", &Celcius); Fahr = (Celcius * 9) / 5; Fahr += 32; printf ("The converted temperature of %d in Fahreight is: %d\n", Celcius, Fahr); case 2: printf ("Please type the temp in Fahrenheit"); scanf ("%d", &Fahr); Celcius = (Fahr - 32) * 5; Celcius /= 9; printf ("The converted temperature of %d in Celcius is: %d\n", Fahr, Celcius); } return 0; } 

您的程序调用未定义的行为 。 使用错误的转换说明符调用UB。 要扫描double使用%lf说明符(您的编译器警告已经建议)。

 scanf ("%lf", &Celcius); 

样品运行 。

对于打印双精度和浮点数,您可以使用%g%f说明符。 如果用户输入无效,您还应该在switch中处理默认情况。 可能通过向用户打印有用的错误消息。

还建议你break; 在每个switch语句之后,以防止执行其他case语句,除非首选该行为。