gpt4 book ai didi

c - 我不知道为什么它可以在计算上运行?

转载 作者:太空宇宙 更新时间:2023-11-04 07:51:46 25 4
gpt4 key购买 nike

我的程序是关于制作水费单的。我在计算部分运行时遇到了问题,当我输入任何数据时它只显示 0。计算是amount=sqrfeet*2.05;是因为 float 部分吗??我正在使用 if else 语句。

int main()
{ char ch;
int a;
float amount, sqrfeet;
start:
printf("\n-------------Selangor Water Bill--------------\n");
printf("\n1.Domestic\n");
printf("\n2.Commercial\n");
printf("\n3.Industrial");
printf("\nChoose one of the category:",a);
scanf("%d",&a);
system("CLS");
if (a!=1&&a!=2&&a!=3){
goto start;
}
if (a=1){
printf("\n1.Domestic");
printf("\nEnter the amount of consumption water per sqrfeet in 35days:");
scanf("%f",&amount);
if(sqrfeet<=35){
amount=sqrfeet*0.57;
}
else if(sqrfeet>35&&sqrfeet<=50){
amount=sqrfeet*1.03;
}
else if (sqrfeet>50){
amount=sqrfeet*2.00;
}
printf("\nTotal Amount is RM%.2lf", amount);
}
else if(a=2){
printf("\n2.Commercial");
printf("\nEnter the amount of consumption water per sqrfeet in
35days:");
scanf("%f",&amount);
if(sqrfeet<=35){
amount=sqrfeet*2.07;
}
else if(sqrfeet>35&&sqrfeet<=50){
amount=sqrfeet*2.28;
}
printf("\nTotal Amount is RM%.2lf", amount);
}
else if (a=3){
printf("\n3.Industrial");
printf("\nEnter the amount of consumption water per sqrfeet in 35days:");
scanf("%f",&amount);
if(sqrfeet<=35){
amount=sqrfeet*2.49;
}
else if(sqrfeet>35&&sqrfeet<=50){
amount=sqrfeet*2.70;
}
printf("\nTotal Amount is RM%.2lf", amount);
}

printf("\nPress'q' to quit ");
scanf("%c",&ch);
return 0;
}

最佳答案

I don't know why it can run on calculation?

要么编译器很弱,要么警告没有完全启用。

节省时间并启用所有警告并接收如下所示的警告。这将有助于定位许多(但不是全部)问题。

// gcc example
gcc -std=c11 -O3 -pedantic -Wall -Wextra -Wconversion -c ...

warning: suggest parentheses around assignment used as truth value [-Wparentheses]

 if (a = 1) {

编译器看到这个赋值并建议if ((a = 1)) {来平息警告。然而,OP 当然不希望在这里进行分配,而是进行比较。 @dbush

 if (a == 1) {

warning: 'sqrfeet' is used uninitialized in this function [-Wuninitialized]

代码在分配之前使用 sqrfeet。当然 scanf("%f",&sqrfeet); 是需要的。 @Tomek Piechocki

// scanf("%f",&amount);
scanf("%f",&sqrfeet);
if(sqrfeet<=35){

warning: too many arguments for format [-Wformat-extra-args]

printf() 调用格式错误。

// printf("\nChoose one of the category:", a);
printf("\nChoose one of the category:");

warning: conversion to 'float' from 'double' may alter its value [-Wfloat-conversion]

0.57 是一个 double。没有理由将 float 用于典型的 float 学运算。使用 double。保存 float 用于大型阵列或时序关键问题。

// float amount, sqrfeet;
//scanf("%f", &amount);
double amount, sqrfeet;
scanf("%lf", &amount);

amount = sqrfeet * 0.57;

如果您想继续使用 float,请使用 float 常量:0.57f


此外:所有 scanf() 说明符都使用前导空白,c, [, n 除外。添加一个空格以消耗先前输入行的剩余 '\n' (Enter)。

// scanf("%c",&ch);
// v
scanf(" %c",&ch);

关于c - 我不知道为什么它可以在计算上运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53361852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com