【问题标题】:Incompatible type for argument 1 of 'printf' using float constants and variables使用浮点常量和变量的“printf”参数 1 的类型不兼容
【发布时间】:2016-09-15 19:31:40
【问题描述】:

我正在尝试编写一个简单的 C 程序来模拟使用固定价格常量的购物体验,然后要求用户输入他们想要购买的金额。然后将数量和价格相乘以获得总成本。

#define TSHIRT   18.95f
//TSHIRT is a constant float for a fixed price on the cost of a t-shirt

int main(void) {
  float numberOfShirts;
  printf("How many T-Shirts would you like?");
  fflush( stdout);
  scanf("%f", &numberOfShirts);
  printf("You will receive %f shirt(s)", numberOfShirts);
  fflush( stdout);

  //This gets the user's amount of shirts they'd like to buy

  float totalCost = (numberOfShirts * TSHIRT);  //Edit: float totalCostadded
  printf("%f", totalCost);

  //this is supposed to be the total cost (amount * price) and print it, 
  //but I get an error -- "incompatible type for argument 1 of 'printf ".

如何修复它或获得正确的类型以使其正常工作?

【问题讨论】:

  • totalCost 声明未发布。问题喜欢在它的声明中。试试double totalCost = (numberOfShirts * TSHIRT);
  • 另外,请阅读minimal reproducible example
  • 为什么需要float 来表示衬衫的数量?有人会买半件衬衫吗?
  • 我会带上我的无袖衣服,@WeatherVane。我猜这大约是 0.6 件衬衫。 :)
  • @Weather Vane 省略换行允许提示和输入出现在同一行。使用'\n' 会改变用户体验。 OP 所做的很好,并建议在提示可能缺少最终的 '\n' 时使用 fflush(stdout)

标签: c variables floating-point constants


【解决方案1】:

您没有定义“totalCost”。确保它也是一个浮点数。顺便说一句,你所做的有点冒险,在你的 scanf 中捕获一个浮点数,如果用户不小心输入了一个字母,你的程序就会崩溃。更好的是从 scanf 接收一个字符串,然后检查其内容并将其转换为浮动,或者向用户报告错误。

【讨论】:

  • 如果用户输入错误,程序不一定会崩溃。当然scanf() 不会崩溃,但它也不会设置numberOfShirts 的值。该变量未初始化,因此随后读取其值将调用未定义的行为。这很可能会表现为奇怪的输出。
  • 请注意,在发布此答案后,类型 float 已(由 OP)添加到问题中。但是,它似乎无法解决问题,即printf() 函数的参数 1 的类型(格式字符串)。
【解决方案2】:

您的代码中有各种错误:您没有声明变量totalCost,将其声明为float 可以解决您的类型问题。 您还需要包含 stdio.h 并且缺少右括号。 这个版本适合我:

#include <stdio.h>
#define TSHIRT   18.95f
//TSHIRT is a constant float for a fixed price on the cost of a t-shirt

int main(void) {
    float numberOfShirts;
    printf("How many T-Shirts would you like?");
    fflush( stdout );
    scanf("%f", &numberOfShirts);
    printf("You will receive %f shirt(s)",numberOfShirts);
    fflush( stdout );

    //This gets the user's amount of shirts they'd like to buy

    float totalCost = (numberOfShirts * TSHIRT);
    printf("%f", totalCost);
}

【讨论】:

  • 货币和二进制浮点数有很多个问题。 IMO,使用 float 而不是 double 会让事情变得更糟。
  • 你可能是对的。然而,这个例子似乎是 OP 的第一个 C 程序之一,问题更多的是 C 编程语言的一般结构和基本类型,而不是将货币建模为浮点数所产生的问题。
  • 通过使用18.95ffloat totalCostprintf("%f", totalCost); 现在可以向学习者解释为什么一件衬衫的结果是18.950001 而不是18.95。如果代码使用了double,这个问题可以留到以后。
  • 再一次,金钱的精度为 10e-2。即便是float 也太过分了,但double 在这方面更糟糕。
  • 我知道我没有使用 并且忘记初始化 totalCost,我的问题是帖子中指出的参数 1 的不兼容类型。我刚刚发布了代码来看看我在做什么。我只想知道如何通过不兼容类型的参数 1。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-26
  • 2015-04-04
  • 2021-04-09
  • 2012-08-06
  • 2015-10-07
相关资源
最近更新 更多