在我对编程作业的介绍中,我遇到了一个问题。我必须创建一个运输计算器,该计算器将根据包裹的重量和发送包裹的距离来运输包裹。他们只会运送不超过10磅的包裹。
收费基于每500英里的运输。它们没有按比例分配,即600英里与900英里相同,即600英里计为500英里的2个分段。
这是他们给我的桌子:
每500英里已运送包裹的重量率
2磅或以下1.50美元
多于2但不超过6 $ 3.70
多于6但不超过10 $ 5.25
问题是每次我输入:
重量:1.0
里数:2000
假设是6.00美元,我会得到58.50美元。这是我的下面的代码。顺便说一句,我不能使用循环。
#include <stdio.h>
int main(void){
float weight, shippingCharge;
int miles, mTotal, mModule, fTotal;
printf("Weight: ");
scanf("%f", &weight);
printf("Miles: ");
scanf("%d", &miles);
mTotal = miles / 500;
mModule = miles % 500;
if(mModule > 0){
fTotal = mTotal + 1;
}
if( weight <= 2){
shippingCharge = fTotal * 1.50;
printf("Your shipping charge is $%.2f\n", shippingCharge);
}else{
if(weight >= 2 && weight <= 6){
shippingCharge = fTotal * 3.70;
printf("Your shipping charge is $%.2f\n", shippingCharge);
}else{
if(weight >= 6 && weight <= 10){
shippingCharge = fTotal * 5.25;
printf("Your shipping charge is $%.2f\n", shippingCharge);
}else{
printf("Sorry, we only ship packages of 10 pounds or less.");
}
}
}
return 0;
}
最佳答案
如果距离是500的精确倍数,则无需初始化fTotal
-在这种情况下,需要将其设置为mTotal
。
所以改变:
if(mModule > 0){
fTotal = mTotal + 1;
}
为此(例如):
fTotal = mTotal + (mModule > 0) ? 1 : 0;
不使用三元运算符的方法:
if(mModule > 0) {
fTotal = mTotal + 1;
} else {
fTotal = mTotal;
}
关于c - C语言编写家庭作业简介,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24541863/