【发布时间】:2023-03-22 07:20:01
【问题描述】:
所以我的问题是我正在尝试创建一个税收程序,该程序获取用户输入的收入、状态,然后打印出结果。我可以毫无错误地完成这一切。一旦我尝试将它放入一个会提示用户“你想再次计算吗?”的 while 循环中。用户可以输入y/n。 “n”结束节目,“y”需要重复节目,用户再次输入信息等等。我无法让程序让用户为变量输入新值。它只会重复结果。有人可以帮我弄清楚吗?我已经尽我所能,并检查了我可以在哪里以及其他人做什么,对我不起作用。任何帮助表示赞赏!
#include <iostream>
#include <string>
using namespace std;
double income, incomeTax;
char maritalStatus;
char again = 'Y';
int main() {
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
income = -1;
//Taxable Singles
const double ts1 = 863;
const double ts2 = 2588;
const double ts3 = 4313;
//Taxable Marriage
const double tm1 = 1726;
const double tm2 = 5176;
const double tm3 = 8626;
//Tax Rates
const double tr1 = .023;
const double tr2 = .033;
const double tr3 = .052;
const double tr4 = .075;
double t1, t2, t3;
//Add variable
const double as1 = 25, as2 = 85, as3 = 181;
const double am1 = 40, am2 = 175, am3 = 390;
//Addition variable simplified
double a1, a2, a3;
//const strings
const string s = "single", m = "joint";
string status;
int i = 0;
//Beginning of Loop
while (again == 'y' || again == 'Y') {
while (income < 0) {
cout << "Please enter your taxable Income." << "\n (This must be a positive value): " << endl;
cin >> income;
if (cin.fail() || income < 0) {
cout << "Please try again. Needs to be a positive number." << endl;
cin.clear();
cin.ignore(40, '\n');
income = -1;
}
}
while (maritalStatus == false) {
cout << "Please enter m if married and filing joint return," <<
"\n or s if filing a single return: ";
cin >> maritalStatus;
if (maritalStatus != 's' && maritalStatus != 'm') {
cout << "Please try again. Needs to be a 's' or 'm'." << endl;
cin.clear();
cin.ignore(40, '\n');
maritalStatus = false;
}
}
if (maritalStatus == 's') {
t1 = ts1;
t2 = ts2;
t3 = ts3;
a1 = as1;
a2 = as2;
a3 = as3;
status = s;
}
else if (maritalStatus == 'm') {
t1 = tm1;
t2 = tm2;
t3 = tm3;
a1 = am1;
a2 = am2;
a3 = am3;
status = m;
}
if (income > 0 && income <= t1) {
incomeTax = (income - (0)) * tr1;
}
else if (income > t1 && income <= t2) {
incomeTax = (income - (t1 - 1)) * tr2 + a1;
}
else if (income > t2 && income <= t3) {
incomeTax = (income - (t2 - 1)) * tr3 + a2;
}
else if (income > t3) {
incomeTax = (income - (t3 - 1)) * tr4 + a3;
}
cout << "Your taxable income is " << "$" << income << endl;
cout << "and you're filing a" << status << " return." << endl;
cout << "Your income tax will be " << "$" << incomeTax << endl;
cout << "Go again? (y/n) ";
cin >> again; //change control variable
}// end loop
system("pause");
return 0;
}
【问题讨论】:
-
手动单步调试代码。如果你记下变量的值,你会很容易看到你的问题。
-
您应该将整个事情简化为最基本的循环(即删除所有不要求用户再次访问的内容)。这里有太多代码需要查看。如果您只有 10 行,您可能会自己找到问题,或者至少其他人会更容易找到问题。您可以随时edit您的问题。
-
在查看了发生的情况后,我能够弄清楚。虽然由于某种原因它不能正确四舍五入....
标签: c++ while-loop do-loops