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

时间:2014-01-03 23:51:32

标签: c

这是我在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 <stdio.h>

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;

} 

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:2)

您的程序会调用未定义的行为。使用错误的转换说明符调用UB。要扫描double,请使用%lf说明符(您的编译器警告已经暗示了这一点)。

scanf ("%lf", &Celcius);   

示例run