带有循环的阿姆斯特朗数 - c ++

时间:2014-11-14 22:34:29

标签: c++ loops

我试图让用户输入一个号码,告诉他们是否Armstrong number然后询问他们是否要再次重复这个号码。 我试着多次写它但它不起作用! 当我进入153时,它给了我“这不是阿姆斯特朗号”。 (在其他声明中) 我真的搞砸了,我不知道该怎么做:“(

    #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 个答案:

答案 0 :(得分:0)

您发布的代码有几个问题,由于格式错误而无法立即显现。格式化对人类很重要,因为它显示了程序的控制流程。以下是重新格式化代码的一部分(使用clang格式),以便您可以观察到问题:

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;
  }
}