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

Armstrong number with loop - c++

本文关键字:c++ 阿姆斯特朗 循环      更新时间:2023-10-16

我试图让用户输入一个数字,告诉他们是否是阿姆斯特朗的数字,然后问他们是否要再次重复。我尝试多次编写它,但没有用!当我输入153时,它给了我"这不是阿姆斯特朗数字"。(在 else 语句中)我真的搞砸了,我不知道该怎么办:"(

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

您发布的代码有几个问题,由于格式不正确,这些问题不会立即显现出来。格式化对人类很重要,因为它使程序的控制流变得明显。以下是重新格式化的代码的一部分(使用 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;
  }
}