我正在开展一项应该对人们最喜欢的饮料进行调查的作业。理想情况下,它将继续要求用户为他们希望包括的每个人提交喜爱的饮料。当用户完成所有投票后,他或她输入-1并显示计数。我注意到的唯一问题是,当结果打印出来时,我会得到每种饮料的任意大数字。我仍然是编码的新手,甚至更新的C ++,但它是否与switch语句的范围有关?它似乎根本没有增加饮料的数量:/。
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int input, vcoff, vtea, vcoke, voj, personNumber = 1;
cout << "Welcome to the favorite beverage survey. Our beverage options are: "<< endl;
cout << "1.Coffee 2.Tea 3.Coke 4.Orange Juice" << endl;
cout << endl;
cout << "Please input the favorite beverage of person # " << personNumber << ": Choose 1, 2, 3, or 4 from the"<< endl << "above menu or -1 to exit the program."<< endl;
cin >> input;
while (input < -1)
{
cout << "That is not an option. Please reenter a valid number: " << endl;
cin >> input;
}
while (input > 0)
{
switch(input)
{
case 1: vcoff++;
break;
case 2: vtea++;
break;
case 3: vcoke++;
break;
case 4: voj++;
break;
default: cout << "Sorry, that's not a menu item. Please try again: " << endl;
cin >> input;
}
personNumber++;
cout << "Please input the favorite beverage of person # " << personNumber << ": Choose 1, 2, 3, or 4 from the"<< endl << "above menu or -1 to exit the program."<< endl;
cin >> input;
}
if (input = -1)
{
cout << "The total number of people surveyed is " << personNumber << ". The results are as follows:" << endl;
cout << "Beverages Votes" << endl << "**********************" << endl;
cout << "Coffee: " << vcoff << endl;
cout << "Tea: " << vtea << endl;
cout << "Coke: " << vcoke << endl;
cout << "Orange Juice: " << voj << endl;
}
return 0;
}
答案 0 :(得分:3)
你错过了变量的初始化。如果你不这么说,局部变量不会初始化为0。
这意味着起始值可以是任何不可预测的值,这可以解释您发现奇怪的数字。
尝试:
int input=0, vcoff=0, vtea=0, vcoke=0, voj=0, personNumber = 1;
答案 1 :(得分:1)
而不是int input, vcoff, vtea, vcoke, voj, personNumber = 1;
执行int input = 0, vcoff = 0, vtea = 0, vcoke = 0, voj = 0, personNumber = 1;
初始化变量。