我哪里错了?我没有得到预期的输出
Where do I wrong ? I don't get expected output
我试着按照问题写代码。但我面临四舍五入的问题。谁能解释我在哪里遇到问题?
M=12, T=20, X=8 tip=(20×12)/100=2.4 tax=(8×12)/100=0.96 final
price=12+2.4+0.96=15.36 Officially, the price of the meal is .36,
but rounded to the nearest
dollar (integer), the meal is .
这是我的完整代码:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int t, x;
double m;
scanf("%lf", &m);
scanf("%d", &t);
scanf("%d", &x);
double tip, tax;
tip= m*t/100;
tax= t*x/100;
int total= (int)(round( tip + tax +m ));
printf("The final price of the meal is $%d.", total);
return 0;
}
当我输入 15.91,15,10
时,它显示输出 19
而不是 20
我哪里出错了?
当你这样做时
tax= t*x/100;
你正在进行整数除法,所以它会被四舍五入。
您将得到 15*10/100 = 1,而不是 1.5
此外,在您提出问题时,您使用的是 t*x
而不是 m*x
M=12, T=20, X=8
tip=(20×12)/100=2.4
T M
tax=(8×12)/100=0.96
X M
改为
tip= m*t/100.0;
tax= m*x/100.0;
你会得到预期的 20 作为最终结果
我试着按照问题写代码。但我面临四舍五入的问题。谁能解释我在哪里遇到问题?
M=12, T=20, X=8 tip=(20×12)/100=2.4 tax=(8×12)/100=0.96 final price=12+2.4+0.96=15.36 Officially, the price of the meal is .36, but rounded to the nearest dollar (integer), the meal is .
这是我的完整代码:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int t, x;
double m;
scanf("%lf", &m);
scanf("%d", &t);
scanf("%d", &x);
double tip, tax;
tip= m*t/100;
tax= t*x/100;
int total= (int)(round( tip + tax +m ));
printf("The final price of the meal is $%d.", total);
return 0;
}
当我输入 15.91,15,10
时,它显示输出 19
而不是 20
我哪里出错了?
当你这样做时
tax= t*x/100;
你正在进行整数除法,所以它会被四舍五入。
您将得到 15*10/100 = 1,而不是 1.5
此外,在您提出问题时,您使用的是 t*x
而不是 m*x
M=12, T=20, X=8
tip=(20×12)/100=2.4
T M
tax=(8×12)/100=0.96
X M
改为
tip= m*t/100.0;
tax= m*x/100.0;
你会得到预期的 20 作为最终结果