C++ 寄送分配将自动终止

  • 本文关键字:终止 分配 C++ c++
  • 更新时间 :
  • 英文 :


您好,我的程序在计算运费后自动终止。你能告诉我我做错了什么吗?另外,我的运费看起来准确吗?非常感谢!

#include <iostream>
#include<iomanip>
using namespace std;
int main() {
const int distanceunit = 500;
double rate = 0, shippingcost=0;
int weight=0, distance=0, Distanceunit2=0;
cout << setprecision(2) << fixed;
cout << "How much does the package weigh in pounds?";
cin >> weight;
//Shipping rate`---------------------------------------------------------------------------------------
//if (weight <= 0) {
//  cout << "The weight should be greater than 0" << endl;
//}//need to include else
//if (weight >20) {
//  cout << "The weight should be 20" << endl;
//}
//else {
//  cout << "How far will the package be going?"<<endl;
//  cin >> distance;
//}
if (weight <= 0 || weight >20) {
cout << "We only accept packages between 1 to 20 kg."<<endl;
cout << "Enter new weight"<<endl;
cin >> weight;
}
else {
cout << "Enter the distance to be shipped(in miles):";
cin >> distance;
}

if (distance < 10 || distance>3000) {
cout << "The distance you entered is not in the mn and max range" << endl;
cout << "Enter new distance" << endl;
cin >> distance;
}
//--------------------------------------------------------------------------------------
Distanceunit2 = distance / distanceunit;
if (weight <= 2) {
rate = 1.10;
}
else if (weight > 2 && weight <= 6) {
rate = 2.20;
}
else if (weight > 6 && weight <= 10) {
rate = 3.70;
}
else {
rate = 4.80;
}
if (distance%distanceunit != 0) {
shippingcost = Distanceunit2 * rate;
}
else {
shippingcost = rate;
}

cout << "The cost to ship a package that weighs " << weight
<< " kilograms for a distance of " << distance
<< " miles is $" << shippingcost << endl << endl;

return 0;
}

另一个问题是它会验证我的体重一次,但在第二次尝试时,它会自动进入 else 块。因此,如果我为我的体重输入 0,它说它不能是 0。我再次尝试 21,它会自动询问我的距离,而不是再次验证它。它对我的距离做了同样的事情。

这是一个可能的(但经过最低限度测试(的提示代码。

注意:代码不会检测或从无效的用户输入(即字母而不是数字(中恢复。

int promptForInt(std::string promptTxt, 
std::string label, 
std::string units)
{
int t = 0;
std::cout << promptTxt;  
cin >> t;
cout << "n  " << label << "  " << t 
<< "  " << units << std::endl;
return t;
}

以及可能的(最低限度测试的(提示/响应用法。

注意:这是一个无限循环,您可能希望避免。

weight = promptForInt("n  How much does the package weigh in pounds?",
"weight:", "pounds");
// range check prompt loop
while ((weight <= 0) || (weight >20))
{
cout << "n  We only accept packages between 1 to 20 kg."<<endl;
weight = promptForInt(
"n  How much does the package weigh in pounds?", 
"weight:", "pounds");
}

你应该寻找其他提示示例,因为我的工作是在嵌入式系统中,(所以这不是我通常的努力(。我的团队需要使用更"复杂"的方法(研究TL1,snmp,也许还有基于"telnet"curses的ui(。

最新更新