int main () {
int num1, num2;
int cnt = 1;
if (cin >> num1){
while (cin >> num2){
if (num1==num2){
++cnt;
} else {
cout << num1 << " is " << cnt << " times" << endl;
cnt = 1;
num1 = num2;
}
}
}
cout << num1 << " is " << cnt << "-times" << endl;
}此代码接受一行数字,并输出每个数字输入的次数。我不明白为什么会有num1=num2。删除它后,程序输出输入的第一个数字,这使我相信我不知道cin在循环中是如何工作的。
我现在想的是,第一个数字进入if (cin >> num1),,它一直坐在这里,下一个相同的数字不会覆盖num1整数。第二位和其余的数字每次都被while (cin >> num2)覆盖,直到有一个不同的数字为止,这使得else可以执行,并输出一直存储在num1中的数字。
使用num1=num2,它改变了if(cin>> num1)中的num1,整个过程又开始了。我说的对吗?
这也很奇怪,最后的cout可能肯定在第一个if体内,但它可能不会,它无论如何工作.
Edit1:使用num1=num2;我输入1 1 2 2 3 3 3,作为一行输出
1 is 2 times
2 is 2 times
3 is 3 times. 不含num1=num1;
1 is 2 times
1 is 1 times
1 is 1 times
1 is 1 times
1 is 1 times发布于 2018-09-07 10:20:06
cin >> num1试图从标准输入中读取一个数字到num1变量中。如果成功,if的主体将被执行。否则(例如,如果用户输入一个数字以外的其他内容或立即按下Ctrl/Ctrl),我们将直接跳到if之后的代码。这种事只发生一次。
cin >> num2对num2变量也做了同样的事情,但这次它是在while而不是if中。因此,如果输入操作成功,会执行while循环的主体,然后再次执行cin >> num2,直到它最终失败。
我不明白为什么会有
num1=num2。
正如我所说的,cin >> num1只执行一次(它不在任何循环中)。因此,如果您从未重新分配num1,它将始终保留输入的第一个值。但是你不想那样,你想要它包含你目前正在计算的值。这就是为什么那个任务在那里。
使用num1=num2,它改变了if中的num1 (cin>>,num1),整个过程又开始了。我说的对吗?
不,cin >> num1再也不会执行了。不是在一个循环里。只有cin >> num2被多次执行,因为这是while循环的一部分。
这也很奇怪,最后的cout可能会确定在第一个如果身体,它可能不会,它无论如何工作.
如果第一个输入操作失败,它将立即跳转到身体的外部。如果存在cout语句,这将意味着即使第一个输入失败,也将执行它。在这种情况下,num1将被未初始化,因此使用它将调用未定义的行为。因此,该语句不应该在if之外。
发布于 2018-09-07 10:19:52
#include <iostream>
int main () {
int num1, num2;
int cnt = 1;
if (std::cin >> num1) { // if a valid integer can be extracted from cin
while (std::cin >> num2) { // do as long as valid integers are extracted from cin
if (num1 == num2) { // if the first extracted int matches the next one
++cnt; // increase the count
}
else { // if it is a different int then do some output and
std::cout << num1 << " is " << cnt << " times\n";
cnt = 1; // reset the counter and
num1 = num2; // remember the new extracted number for
// the next iteration of the while-loop
// since only num2 will be read again from cin
}
}
}
std::cout << num1 << " is " << cnt << "-times\n";
}由于main()中的最后一行没有意义,如果没有有效的输入,我建议提前退出:
#include <cstdlib>
#include <iostream>
int main () {
// ...
if (!( std::cin >> num1 ))
return EXIT_FAILURE;
while (std::cin >> num2) {
if (num1 == num2) {
// ...它还减少了缩进水平,从而提高了可读性。
发布于 2018-09-07 10:19:32
我理解代码所做的是计算和显示一个数字的连续表象数,这样它就不会适用于无序列表。
尽管如此,它的工作方式基本上如下:
num1中。num2。num1和num2相同,则增加计数器。num1)更改为新读取的数字(num2)。https://stackoverflow.com/questions/52220161
复制相似问题