C 为什么我的输出为0.0
代码:C 为什么我的输出为0.0,c,C,代码: 将此分配放入折扣价格=0.05*价格+价格-0.1*价格在scanf(“%f”、&price)之后会得到正确的结果,否则在键入数字作为价格之前,折扣价格已经设置为未初始化的值 您的问题是在获得折扣之前计算折扣价格!在代码中,首先通过“折扣价格=0.05price+价格-0.1price;”计算折扣价格,然后通过“scanf”(%f),&price)”从键盘读取数字。当您通过“折扣价格=0.05价格+价格-0.1价格”使用价格时,价格值未知,因此您的折扣价格结果是错误的。发生这种情况的原因
将此分配放入
折扣价格=0.05*价格+价格-0.1*价格代码>在scanf(“%f”、&price)之后
会得到正确的结果,否则在键入数字作为价格之前,折扣价格已经设置为未初始化的值
您的问题是在获得折扣之前计算折扣价格!在代码中,首先通过“折扣价格=0.05price+价格-0.1price;”计算折扣价格,然后通过“scanf”(%f),&price)”从键盘读取数字。当您通过“折扣价格=0.05价格+价格-0.1价格”使用价格时,价格值未知,因此您的折扣价格结果是错误的。发生这种情况的原因是您试图从价格中计算值,而价格未初始化,因此您必须先获得价格,然后才能从中计算
Enter the total price:
1234
congrats you have scored a discount of 10 percent. your total bill amount is:0.0
#包括
int main(){
浮动价格;
浮动税=0.0f;
浮动折扣价格=0.0f;
printf(“输入总价:”);
scanf(“%f”和“价格”);
税=0.05f*价格;
折扣价格=0.05*价格+价格-0.1*价格;
如果(价格>1000.00)
printf(“祝贺您获得了10%的折扣。您的账单总金额为:%0.1f”,折扣价格);
其他的
printf(“您的账单总额为:%f”,价格);
返回0;
}
正如您在上面的代码中所看到的,我们首先从用户处获取值,然后计算税费和折扣价格。price
在使用前未初始化。price=0.05*price+price-0.1*price
您希望此时的price
的值是多少?请确保已初始化所有内容,并使用一些基本编译标志编译代码,例如-Wall-Werror-Wextra
如果使用gcc
/clang
。考虑使用和调试您的代码。您的代码不使用<代码>税号>代码>,不初始化<代码>价格< /代码>——如果正确使用编译器,您将被警告这两种情况。此外,请确保检查scanf
浮动折扣价格=0.05*价格+价格-0.1*价格的返回值代码>根据当时表达式的值设置折扣价格。以后更改价格
不会更新折扣价格
。为什么它已经设置为0?@ojaswi您希望自动的默认值是什么?@ojaswi它不一定是0
。类似浮动价格的变量代码>未初始化,可以有任何值,包括可能触发浮点异常的无效值。使用前必须初始化price
,否则行为未定义。@ojaswi dxiv是正确的。但是你的问题是在你得到它之前计算折扣价格!在代码中,首先通过“折扣价格=0.05*price+price-0.1*price;”计算折扣价格,然后通过“scanf”(%f),&price)”从键盘读取数字。按“折扣价格=0.05*价格+价格-0.1*价格”使用价格时,价格值未知,因此您的折扣价格结果是错误的。
Enter the total price:
1234
congrats you have scored a discount of 10 percent. your total bill amount is:0.0
#include<stdio.h>
int main() {
float price;
float tax = 0.0f;
float discounted_price = 0.0f;
printf("Enter the total price: ");
scanf("%f", &price);
tax = 0.05f * price;
discounted_price = 0.05*price+price-0.1*price;
if(price>1000.00)
printf("congrats you have scored a discount of 10 percent. your total bill amount is:%0.1f", discounted_price);
else
printf("your total bill is:%f",price);
return 0;
}