[英]in this if statement to used count how many consecutive times each distinct value appears, why doesn't it print the final value?
此示例來自 c++ 入門第 5 版,使用 if 編寫程序來計算每個不同值在輸入中連續出現的次數
如果我們給這個程序以下輸入:
42 42 42 42 42 55 55 62 100 100 100
那么 output 應該是
42 occurs 5 times
55 occurs 2 times
62 occurs 1 times
100 occurs 3 times
但是當我嘗試時,它不會打印最后一個值或計數。 這是代碼:
#include <iostream>
int main()
{
// currVal is the number we're counting; we'll read new values into val
int currVal = 0, val = 0;
// read first number and ensure that we have data to process
if (std::cin >> currVal) {
int cnt = 1; // store the count for the current value we're processing
while (std::cin >> val) { // read the remaining numbers
if (val == currVal) // if the values are the same
++cnt; // add 1 to cnt
else { // otherwise, print the count for the previous value
std::cout << currVal << " occurs "
<< cnt << " times" << std::endl;
currVal = val; // remember the new value
cnt = 1; // reset the counter
}
} // while loop ends here
// remember to print the count for the last value in the file
std::cout << currVal << " occurs "
<< cnt << " times" << std::endl;
} // outermost if statement ends here
return 0;
}
正如上面提到的那樣,您可以使用 Ctrl+D 或者您可以使用以下語句,例如:如果用戶輸入 -1,則循環中斷。
#include <iostream>
int main()
{
// currVal is the number we're counting; we'll read new values into val
int currVal = 0, val = 0;
// read first number and ensure that we have data to process
std::cout << "-1 to exit\n";
if (std::cin >> currVal) {
int cnt = 1; // store the count for the current value we're processing
while (std::cin >> val && val != -1) { // read the remaining numbers
if (val == -1) // if the user enters -1 the loop breaks
break;
else if (val == currVal) // if the values are the same
++cnt; // add 1 to cnt
else { // otherwise, print the count for the previous value
std::cout << currVal << " occurs "
<< cnt << " times" << std::endl;
currVal = val; // remember the new value
cnt = 1; // reset the counter
}
} // while loop ends here
// remember to print the count for the last value in the file
std::cout << currVal << " occurs "
<< cnt << " times" << std::endl;
} // outermost if statement ends here
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.