c - 使用浮点常量和变量的 'printf' 参数 1 的类型不兼容

标签 c variables floating-point constants

我正在尝试编写一个简单的 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”。确保它也是一个 float 。顺便说一句,你所做的事情有点冒险,在你的 scanf 中捕获一个 float ,如果用户不小心输入了一个字母,你的程序将会崩溃。更好的方法是从 scanf 接收一个字符串,然后检查其内容并将其转换为浮点型,或者向用户报告错误。

关于c - 使用浮点常量和变量的 'printf' 参数 1 的类型不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39518955/

相关文章:

javascript - 将 HTML 文本设置为 JS 变量

variables - 如何在 Jekyll 中的 DRY 模板和 ninclude 之间传递变量

java - 通过输入数据创建多个变量

c++ - 中断 NaN 或 infs

c - 如何通过串口将整数发送到arduino?

c - 为什么我的程序不会标记字符?

c - 如何在 FatFs 中获得最大的空闲连续内存块

c - 字符串的实现

php - 在 MySQL 数据库中存储纬度和经度值的问题

python - 导入文本文件出错