【问题标题】:C Student Assignment, ‘%f’ expects argument of type ‘float *’, but argument 2 has type ‘double *’ [duplicate]C 学生作业,“%f”需要“float *”类型的参数,但参数 2 的类型为“double *”[重复]
【发布时间】:2014-03-23 14:15:37
【问题描述】:

我正在处理一项任务,我收到以下警告:

C4_4_44.c:173:2: warning: format ‘%f’ expects argument of type ‘float *’, 
but argument 2 has type ‘double *’ [-Wformat]

变量在main中声明为:

double carpetCost;

我将函数调用为:

getData(&length, &width, &discount, &carpetCost);

函数如下:

void getData(int *length, int *width, int *discount, double *carpetCost)

{

    // get length and width of room, discount % and carpetCost as input

    printf("Length of room (feet)? ");

    scanf("%d", length);

    printf("Width of room (feet)? ");

    scanf("%d", width);

    printf("Customer discount (percent)? ");

    scanf("%d", discount);

    printf("Cost per square foot (xxx.xx)? ");

    scanf("%f", carpetCost);

    return;

} // end getData

这让我发疯了,因为书上说你不使用 &

scanf("%f", carpetCost); 

当从您传递它的函数访问它时,它是引用。

有什么想法我在这里做错了吗?

【问题讨论】:

  • 您可能想阅读scanf reference
  • 这是为了和printf不一致,为了不容易记住:printf("%f", double_value); scanf("%f", &float_value).
  • @vaxquis 很久以前问过我的问题后才看到这个,想解释一下。我正在上课,进行搜索,并且因为不知道要使用的正确搜索词而感到沮丧,所以我什么也没找到。对不起,如果我给人的印象是我试图使用论坛为我做作业。我实际上是一个 50 多岁的成年人,他坚信自己的工作。和平。

标签: c reference double


【解决方案1】:

改变

scanf("%f", carpetCost);

scanf("%lf", carpetCost);

%f 转换规范用于float * 参数,您需要%lf 用于double * 参数。

【讨论】:

  • 谢谢!我刚看到你的回复,我就明白了!伙计,你们太快了!非常感谢!
【解决方案2】:

使用%lf 规范代替double * 参数。

scanf("%lf", carpetCost); 

【讨论】:

  • 我只是想通了,然后看了看你的答案。小子,我是不是觉得很傻! :-) 非常感谢您的快速回复!
【解决方案3】:

如果您正在扫描双精度类型的变量,请使用 %lf 而不是 %f。您还可以从讨论的线程的链接中详细检查%lf%f

Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?

【讨论】:

    猜你喜欢
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 2018-07-06
    • 2022-01-21
    • 2014-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多