当年龄超出18-25岁时,我似乎无法将附加费变量等于0。
当输入包含附加费但程序附加费必须等于0时,程序运行正常,表示未初始化。
我的代码如下。
#include<iostream>
using namespace std;
int main()
{
int age, accidents, basic = 500, surcharge, program, total;
char safety;
cout << "Enter your age: " << endl;
cin >> age;
cout << "Enter # of accidents: " << endl;
cin >> accidents;
cout << "Did you attend a driver saftey program? y/n: ";
cin >> safety;
if (age < 18 || accidents >= 6)
{
cout << "You are not eligible for insurance";
}
else
if (age >= 18 || age <= 25)
surcharge = 100;
else
surcharge == 0;
if (accidents == 1 && safety == 'n')
program = 50;
else if (accidents == 2 && safety == 'n')
program = 125;
else if (accidents == 3 && safety == 'n')
program = 225;
else if (accidents == 4 && safety == 'n')
program = 375;
else if (accidents == 5 && safety == 'n')
program = 575;
// attended driver safety course
else if (accidents == 1 && safety == 'y')
program = 35;
else if (accidents == 2 && safety == 'y')
program = 100;
else if (accidents == 3 && safety == 'y')
program = 200;
else if (accidents == 4 && safety == 'y')
program = 325;
else if (accidents == 5 && safety == 'y')
program = 500;
else
program = 0;
total = basic + surcharge + program;
cout << "Your total is: " << total << endl;
getchar();
getchar();
return 0;
}
答案 0 :(得分:1)
此时
if (age >= 18 || age <= 25)
surcharge = 100;
else
surcharge == 0; // <--- here
我想你想写
surcharge = 0;
答案 1 :(得分:0)
如果要对其进行初始化,只需将其初始化即可。更改以下行
int age, accidents, basic = 500, surcharge, program, total;
到
int age, accidents, basic = 500, surcharge = 0, program, total;
答案 2 :(得分:0)
我可以看到彼此附近有2个错误。你写道:
if (age >= 18 || age <= 25)
surcharge = 100;
else
surcharge == 0;
应该是:
if (age >= 18 && age <= 25)
surcharge = 100;
else
surcharge = 0;
您需要检查age >= 18
AND(&&
)age <= 25
而非OR(||
)
另一个错误是surcharge == 0
应该是surcharge = 0
(你希望赋值不等)
如果你没有保险,你想在显示错误后退出程序,所以你应该考虑在打印错误信息后返回的地方进行更改:
if (age < 18 || accidents >= 6)
{
cout << "You are not eligible for insurance" << endl;
return 1; // A value > 0 usually denotes an error occurred
}