【问题标题】:C program won't compile despite using proper specifier? [closed]尽管使用了正确的说明符,C 程序仍无法编译? [关闭]
【发布时间】:2015-12-29 15:50:14
【问题描述】:

由于我目前不明白的原因,尽管拥有完成任务所需的一切,但此代码将无法编译。

#include <stdio.h>      /* printf */
#include <math.h>


double resistance;
double voltage;
double current;
double wattage;
int main()
{

    printf("type in resistance\n");
    scanf("%f",resistance);
    printf("type in current");
    scanf("%f",current);
    //voltage = resistance*resistance*current;
    printf("%f Volts",resistance*resistance*current);

    //  return voltage;
}

我不明白的是为什么它不能编译?编译时我不断收到“错误的说明符”消息。我尝试了%lf%f,但它们都不起作用。

【问题讨论】:

  • 仔细看第二个参数scanf
  • 例如GCC 为您提供正确的信息:x.c:13:7: warning: format '%f' expects argument of type 'float *', but argument 2 has type 'double' [-Wformat=]
  • 我不确定我是否明白,它们在我看来都一样。我认为您指的是 scanf("%f",current);
  • 顺便说一句:voltage = resistance*resistance*current 是错误的。应该是voltage = resistance*current

标签: c scanf format-specifiers


【解决方案1】:

您想使用 scanf 为您的双变量分配一个浮点值。参数必须是指针:

int main() {

    printf("\ntype in resistance\n");
    scanf("%lf",&resistance);
    printf("\ntype in current");
    scanf("%lf",&current);
    //voltage = resistance*resistance*current;
    printf("\n%f Volts",resistance*resistance*current);
    // return voltage; 
}

【讨论】:

  • 由于某种原因,我一直得到 0 作为答案?它是使用 * 作为指针而不是乘法吗?
  • double resistance; scanf("%lf",&amp;resistance); --> 添加l.
  • @obito94:输入resistancecurrent的值后打印出来。正如我在下面指出的,您应该使用%lf 读取double 变量。
  • 我现在得到了电阻值,但电流从不显示,并且由于某种原因,以伏特为单位的答案总是 = 电阻
【解决方案2】:

按照 C99 的标准,浮点数没有专用的格式说明符。无论您使用浮点数还是双精度数,都不算数。重要的是,当您使用浮点变量时 printf 会自动将其提升为双精度并显示它。因此 %f 表示双精度或浮点值,而 %Lf 用于长双精度值。

参考:http://www.cplusplus.com/reference/cstdio/printf/

int main() {

   printf("Type in Resistance: ");
   scanf("%lf", &resistance);
   printf("Type in Current: ");
   scanf("%lf", &current);
   printf("%f Volts",resistance*resistance*current);
}

【讨论】:

  • 抱歉,打错了。已更正。
  • 这个答案与 printf() 的格式说明符有关,这不是 OP 的问题。 OP 的问题是scanf() 的格式说明符不正确。使用"%f""%lf" 及其匹配 指针类型至关重要。
【解决方案3】:

不是printf,是scanf:

scanf("%f", resistance);

这应该是:

scanf("%lf", &resistance);

%lf 因为它是双精度,%f 用于浮点数。而&amp;resistance 因为scanf 期待一个指向任何东西的指针,所以它可以写在那里。当您编写 %f 时,printf 只需要一个浮点数,scanf 是一个指向浮点数的指针。 %lfdouble/double*

【讨论】:

  • "%lf" 因为它是double *"%f" 是用于floats *
【解决方案4】:

换行

scanf("%f",resistance);
scanf("%f",current);

scanf("%lf", &resistance);
scanf("%lf", &current);

%f 转换说明符期望相应参数的类型为 float *,但表达式 resistancecurrent 的类型为 double。表达式&amp;resistance&amp;current 具有double * 类型,因此您需要使用%lf 转换说明符(它需要double * 类型的参数)。

【讨论】:

  • 相关问题:花车没有&lt;inttypes.h&gt;
  • @Kay:有一个&lt;float.h&gt;,但它不像&lt;inttypes.h&gt;那样提供任何特定宽度类型或格式化宏。
猜你喜欢
  • 2020-07-08
  • 2018-07-21
  • 1970-01-01
  • 2023-04-05
  • 2022-11-19
  • 1970-01-01
  • 1970-01-01
  • 2013-02-08
  • 2021-08-27
相关资源
最近更新 更多