2014-11-14 64 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