我正在尝试为我正在编写的C ++程序创建里程超时计算功能。我在使用此函数在switch语句中正常工作时遇到问题。我想要达到(或计算)的是里程数超过carSize里程限制*租用的天数。每个carSize都有不同的超额/英里计算率。
到目前为止我的代码是:
double calcMilesFee(int miles, int days, char carSize)
{
double milesFee = 0;
double compactOverageCharge = .05;
double midSizeOverageCharge = .07;
double fullSizeOverageCharge = .09;
int compactDailyMilesLimit = 20;
int midSizeDailyMilesLimit = 25;
int fullSizeDailyMilesLimit = 30;
switch (carSize)
{
case 'c':
case 'C':
{
while (miles > compactDailyMilesLimit * days)
{
milesFee = (miles * days) / compactDailyMilesLimit;
}
if (milesFee > compactDailyMilesLimit)
{
milesFee = milesFee * compactOverageCharge;
cout << "Overage Fee is " << milesFee << endl;
break;
}
}
case 'm':
case 'M':
{
while (miles > midSizeDailyMilesLimit * days)
{
milesFee = (miles * days) / midSizeDailyMilesLimit;
}
if (milesFee > midSizeDailyMilesLimit)
{
milesFee = milesFee * midSizeOverageCharge;
cout << "Overage Fee is " << milesFee << endl;
break;
}
}
case 'f':
case 'F':
{
while (miles > fullSizeDailyMilesLimit * days)
{
milesFee = (miles * days) / fullSizeDailyMilesLimit;
}
if (milesFee > fullSizeDailyMilesLimit)
{
milesFee = milesFee * fullSizeOverageCharge;
cout << "Overage Fee is " << milesFee << endl;
break;
}
}
}
return milesFee;
}
答案 0 :(得分:2)
您的问题包括:
那就是说,这个问题比你做出来的要简单得多:
#include <iostream>
#include <cmath>
double calcMilesFee(int miles, int days, char carSize)
{
const double compactOverageCharge = .05;
const double midSizeOverageCharge = .07;
const double fullSizeOverageCharge = .09;
const int compactDailyMilesLimit = 20;
const int midSizeDailyMilesLimit = 25;
const int fullSizeDailyMilesLimit = 30;
double overageCharge = 0.0;
int dailyMilesLimit = 0;
double milesFee = 0;
switch (carSize)
{
case 'c':
case 'C':
dailyMilesLimit = compactDailyMilesLimit;
overageCharge = compactOverageCharge;
break;
case 'm':
case 'M':
dailyMilesLimit = midSizeDailyMilesLimit;
overageCharge = midSizeOverageCharge;
break;
case 'f':
case 'F':
dailyMilesLimit = fullSizeDailyMilesLimit;
overageCharge = fullSizeOverageCharge;
break;
}
milesFee = std::max(0, miles - (days * dailyMilesLimit)) * overageCharge;
std::cout << "Overage Fee is " << milesFee << std::endl;
return milesFee;
}
正如我在评论中提到的,我建议不要使用浮点进行货币计算,除非您的任务是强制性的。你可以把最终结果作为一个浮点值,但是我写这个我会使用整数精度到一些硬限制(比如十分之一便士)并执行浮点转换一次和最后
答案 1 :(得分:0)
每个案例陈述都应以break
结尾。在您的情况下,如果任何内部if
语句失败,则不会使下一个case语句执行而导致不同的行为。