我剛剛為一個學校專案完成了一個小函式的編碼,并得到了正確的答案。然而,在添加了一個 do-while 回圈(因為它是必需的)之后,我開始遇到問題。第一個回圈作業得很好,我得到了正確的答案(即,如果我在函式中輸入 20,它會輸出 210,這是正確的),但是如果我輸入相同的數字或不同的數字,則該數字將 ON 添加到前一個總計(所以如果我加 1,那么“總計”就是 211)。我希望每個回圈都找到總數,輸出該總數,然后在發生新回圈時重新開始。我該如何解決?
#include <iostream>
using namespace std;
int n, total = 0; /* Global variables since I only have to declare it once rather than two times! */
int sum(int n);
// Recursive version to calculate the sum of
// 1 2 .... n
int main()
{
char choice;
do {
cout << "Enter a positive integer:";
cin >> n;
sum(n);
cout << "The sum of 1 ... " << n << " is: " << total << endl;
cout << "Would you like to try another entry (Y/N): ";
cin >> choice;
}while(choice == 'Y' || choice == 'y');
cout << "Goodbye!" << endl;
return 0;
}
int sum(int n){
if(n == 0)
{
return total;
}
else
{
total = total n;
return sum(n-1);
}
}
uj5u.com熱心網友回復:
您可以嘗試以下代碼sum:
int sum(int n) {
if (n == 1) {
return 1;
} else {
return n sum(n - 1);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/369954.html
