![](/img/trans.png)
[英]How to use scanf to read inputs which are in the form of float1##float2 (i.e., two float numbers separated by two pound signs)
[英]How to use scanf to read a number declared as float?
#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 读取初始价格。
我需要做什么?
谢谢
要将浮点数读入initialPrice
变量,我们应该首先看看scanf
是如何工作的。 正如您在此处看到的, scanf
具有签名:
int scanf(const char *format, ...)
format
参数是一个带有“格式字符串”的字符串,您可以观察到格式字符串或多或少由%[chars][type]
,其中[chars]
是应该读取的最大[chars]
数和[type]
是一组表示参数类型的字符。 在这种情况下,我们不关心输入大小,我们想读入一个浮点数,所以我们使用格式字符串%f
。 现在我们需要提供我们想要读入的变量的地址作为下一个参数,所以我们使用&
字符来获取initialPrice
的地址。 这非常重要,因为没有&
,代码将导致分段错误。 所以,我们的最后一行看起来像
scanf("%f", &initialPrice);
请注意,在要求输入之前打印某种提示是一个好习惯,并且您应该检查scanf
的返回值以确保它等于 1,因为这是您想要读入的变量数量。
这看起来像是一项家庭作业,因此最好由您自己提出解决方案。
不是将 initialPrice 设置为 13.26,而是添加一行代码,调用 scanf 将 initialPrice 的值设置为某物。 scanf 需要将一些消息传递给用户以及 initialPrice 变量以存储用户输入的任何内容。
printf("请输入初始价格值\\n"); scanf("%f\\n",& InitialPrice); 您可以通过添加这几行来编辑您的,并且不要将任何值初始化为“initialPrice = 13.26;” 因为它会取那个值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.