您好我正在尝试解决这段代码问题。我想我已经解决了它,但我正在努力解决的问题是它如何检测我输入的每个数字,以便说出它读取每个数字的次数。
int main()
{
int currentValue = 0, value = 0;
int count = 1;
if (cin >> currentValue) //Get first number to process from user
{
while (cin >> value) //Get subsequent numbers
{
if (value == currentValue) //If subsequent numbers are the first as the first number entered
{
++count; //Add to count for how many there are
}
else //if not
{
cout << currentValue << " occurs " << count << " times" << endl;
currentValue = value; //Remember the new value
count = 1; //Reset counter
}
}
//Prints for the value in the file
cout << currentValue << " occurs " << count << " times" << endl;
}
return 0;
}
我不确定if语句和while语句如何协同工作以及它们之间的关系。发生的是if语句读取第一个数字然后while语句读取后面的数字吗?
答案 0 :(得分:0)
就像你说的那样。 if语句尝试读入currentValue
,而while尝试读入value
。首先执行if语句,然后在条件成立时执行while。他们之间没有依赖关系。