【发布时间】:2015-01-30 18:31:28
【问题描述】:
我正在为一个班级编写一个口味测试程序,它会在我的 if 语句之前运行良好。但是,一旦我进入我的 if 语句,它就不会增加 i,所以它永远不会离开 while 循环。
#include <iostream>
using namespace std;
void main()
{
int i = 0;
int q = 0;
int p = 0;
int c = 0;
char preference;
int x = 0;
cout << "How many taste tests would you like to do?" << endl;
cin >> x;
while (i<x)
{
cout << "Do you prefer Coke, Pepsi, or are they the same? Use c for coke, p for pepsi, and q for the same\n";
cin >> preference;
if (preference == 'q' || preference == 'Q')
{
q = q + 1;
i++;
}
if (preference == 'p' || preference == 'P')
{
p = p + 1;
i++;
}
if (preference == 'c' || preference == 'C')
{
c = c + 1;
i++;
}
}
if (p>q)
{
cout << "Pepsi wins" << endl;
if (c>p)
cout << "Coke wins" << endl;
if (c == p)
cout << "Tie" << endl;
}
}
【问题讨论】:
-
使用调试器,单步执行以
cin >> preference;开头的代码,看看单步执行代码时会发生什么。 -
我认为你正在尝试做类似
if(preference=='q' || preference=='Q')你没有把'放的东西 -
他们在 CS 课程中教授调试吗?好像没有。
-
您的变量
p、P、q等是0,因此在编译时,它不会测试是否存在您认为的匹配。也确定我以前见过这种错误,但不确定我是否能找到重复的。
标签: c++ visual-c++ visual-studio-2012