2014-11-14 37 views
-1

我想讓用戶輸入一個數字,告訴他們,如果它是Armstrong number或不,然後問他們,如果他們想再次重複這一點。 我試着寫了很多次,但沒有奏效! 當我輸入153時,它給了我「這不是阿姆斯特朗號。」 (在else語句) 我真的搞砸了,我不知道該怎麼辦:「(阿姆斯壯數字與循環 - C++

#include <iostream> 
    #include <cmath> 
    using namespace std; 

    int main() { 
    int number, sum=0, num; 
    double y; 
    char x; 

    cout << "Enter a number to check if it is an Armstrong number: "; 
    cin >> number; 
    num = number; 
    while (number != 0) { 
    y = number%10; 
    number = number/10; 
    sum = sum + pow(y,3); 

    if (sum == num) 
    cout << num << "is an Armstrong number."; 
    else 
    cout << num << "is not an Armstrong number."; 

    cout << "do you want to continue? (y/n)"; 
    cin >> x; 
    switch (x){ 
    case 'Y': 
    case 'y': continue; break; 
    case 'N': 
    case 'n': cout << "bye"; break; 
    } 
    } 
    return 0; 
    } 
+1

你不能在'switch'語句中使用'break'打破'while'循環。另外,這裏需要兩個循環 - 一個用於掃描數字的外部循環,一個用於檢查數字的內部循環。 – 2014-11-14 22:37:20

+0

簡而言之,在賦值'sum = sum + pow(y,3)'之後用'}'關閉'while'循環。 – 2014-11-14 22:50:14

+0

另外,您需要計算數字的長度,目前您只能使用3位數字。 – 2014-11-14 23:28:38

回答

0

您發佈的代碼有是因爲不正確的格式不會立即顯現若干問題的格式事宜。人類因爲它使明顯的程序的控制流下面是重新格式化你的代碼的部分(與鏗鏘格式),這樣你可以觀察到的問題:

while (number != 0) { 
    y = number % 10; 
    number = number/10; 
    sum = sum + pow(y, 3); 

    if (sum == num) 
     cout << num << "is an Armstrong number."; 
    else 
     cout << num << "is not an Armstrong number."; 
//... 

應該從這個很明顯,你是測試在計算過程中,這個數字是否是阿姆斯壯的數字,代碼應該是這樣的:

while (number != 0) { 
    y = number % 10; 
    number = number/10; 
    sum = sum + pow(y, 3); 
}  

if (sum == num) 
    cout << num << "is an Armstrong number."; 
else 
    cout << num << "is not an Armstrong number."; 

當然你還需要一個外層循環來詢問用戶是否繼續。

此外,您的測試假設3位數字不一定是真實的,因爲1634也是阿姆斯壯的數字。你需要計算數字。這裏是完整的解決方案:

#include <iostream> 
#include <cmath> 
using namespace std; 

static int digit_count(int num); 
static int armstrong_sum(int num); 
static bool ask_yes_no(const char* question); 

int main() { 
    do { 
    int num; 
    cout << "Enter a number to check if it is an Armstrong number: "; 
    cin >> num; 
    if (num == armstrong_sum(num)) 
     cout << num << " is an Armstrong number." << endl; 
    else 
     cout << num << " is NOT an Armstrong number." << endl; 
    } while (ask_yes_no("do you want to continue?")); 
    cout << "bye" << endl; 
    return 0; 
} 

int digit_count(int num) { 
    int count = 0; 
    for (; num != 0; num /= 10) { 
    count++; 
    } 
    return count; 
} 

int armstrong_sum(int num) { 
    int sum = 0; 
    int count = digit_count(num); 
    for (; num != 0; num /= 10) { 
    sum += static_cast<int>(pow(num % 10, count)); 
    } 
    return sum; 
} 

bool ask_yes_no(const char* question) { 
    for (;;) { 
    char x; 
    cout << question << " (y/n)"; 
    cin >> x; 
    if (x == 'y' || x == 'Y') 
     return true; 
    else if (x == 'n' || x == 'N') 
     return false; 
    } 
} 
+0

謝謝!現在我明白爲什麼輸出錯了:) – 2014-12-15 19:09:33