簡體   English   中英

有沒有辦法在 while 循環中存儲變量?

[英]Is there a way to store a variable during a while loop?

我正在使用 do-while 循環,它會要求用戶輸入正數。 當我輸入零 (0) 數字時,程序將終止。 然后它將計算我輸入的所有數字的總和並顯示它。

#include <iostream>
using namespace std;

int main () {
    
    int end = 0;
    int num1;

        
    do {
        cout << "Enter a number:";
        cin >> num1;
        cout << "\n" << endl;

    } while (end != num1); 

    {
        cout << "sum = " << num1+num1;
    }
}

它是一個簡單的程序。 您可以在其中添加異常代碼

#include <iostream>
using namespace std;

int main() {
  int n=0;
  int sum=0;
  do {
    cin>>n;
    sum+=n;
  }while(n); // this loop will break when n=0
  
  cout<<sum;

}

您需要指定某種sum變量,您將通過輸入的數字增加每次迭代。

可能的解決方案:

#include <iostream>

int main() {
    int sum = 0;
    // '10' can be changed according to how many numbers you want to input
    for (int i = 0; i < 10; i++) {
        int temp;
        std::cin >> temp; 
        sum += temp;
    }
    std::cout << sum << std::endl;
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM