【问题标题】:How to use scanf to read a number declared as float?如何使用 scanf 读取声明为浮点数的数字?
【发布时间】:2020-03-29 15:26:40
【问题描述】:
#include <stdio.h>
int main() {
  float initialPrice, discount, VAT, priceWithVAT, priceWithDiscount;
  initialPrice = 13.26;
  VAT = 0.20;
  discount = 0.125;
  priceWithVAT = initialPrice * (1.0 + VAT);
  priceWithDiscount = priceWithVAT * (1.0 - discount);
  printf("Initial Price %10.2f\n", initialPrice);
  printf(" + VAT @ %4.1f%% %10.2f\n", VAT * 100, priceWithVAT);
  printf(" - discount @ %4.1f%%%10.2f\n", discount * 100, priceWithDiscount);
  return 0;
}

我是 C 编程新手,我被要求修改上述程序,以便在计算之前使用 scanf 读取初始价格。

我需要做什么?

谢谢

【问题讨论】:

标签: c


【解决方案1】:

printf("输入初始价格值\n"); scanf("%f\n",& InitialPrice); 您可以通过添加这几行来编辑您的,并且不要将任何值初始化为“initialPrice = 13.26;”因为它会取那个值。

【讨论】:

    【解决方案2】:

    这看起来像一个家庭作业,所以最好让你自己想出解决方案。

    不是将 initialPrice 设置为 13.26,而是添加一行代码调用 scanf 来设置 initialPrice 的值。 scanf 需要向用户传递一些消息以及 initialPrice 变量来存储用户输入的任何内容。

    【讨论】:

      【解决方案3】:

      要将浮点数读入initialPrice 变量,我们首先应该看看scanf 是如何工作的。 As you can see here,scanf有签名:

      int scanf(const char *format, ...)
      

      format 参数是一个带有“格式字符串”的字符串,您可以观察到格式字符串或多或少由%[chars][type] 组成,其中[chars] 是应该读取的最大字符数,并且[type] 是一组表示参数类型的字符。在这种情况下,我们不关心输入大小并且我们想以浮点数读取,因此我们使用格式字符串%f。现在我们需要提供我们想要读入的变量的地址作为下一个参数,所以我们使用&amp; 字符来获取initialPrice地址 .这非常重要,因为没有&amp;,代码会导致分段错误。所以,我们的最后一行看起来像

      scanf("%f", &initialPrice);
      

      请注意,在要求输入之前打印某种提示是一个好习惯,并且您应该检查 scanf 的返回值以确保它等于 1,因为这是您想要的变量数量读进去。

      【讨论】:

        猜你喜欢
        • 2013-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-01
        • 1970-01-01
        相关资源
        最近更新 更多