带循环的阿姆斯特朗数 - c++
Armstrong number with loop - c++
我试图让用户输入一个数字,告诉他们是否是阿姆斯特朗的数字,然后问他们是否要再次重复。我尝试多次编写它,但没有用!当我输入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;
}
}
相关文章:
- 康斯特指针C++斯特劳斯特鲁普
- C++:根据斯特劳斯特鲁普的例子播种随机数
- C++:斯特劳斯特鲁普iterator_traits示例不编译?
- packaged_task示例问题?斯特劳斯特鲁普示例修改
- Static_cast 对于康斯特来说,会抛弃预选赛
- 输入 A,B 输出 [A,B] 中的所有阿姆斯特朗数 1 和 1<=A<=B<=10^7
- 东康斯泰克普/康斯蒂尼特/康斯特瓦尔在C++20 中允许吗?
- 康斯特正确性建议
- 什么是斯特伦省略?
- 从字符到康斯特* 字符的转换无效,代码有什么问题?
- C++ 斯特劳斯特鲁普的"std_lib_facilities.h"字符串结构 – 警告:无符号表达式的比较
- 程序中的错误,无法在用户给定的间隔之间查找阿姆斯特朗数
- T*上的部分排序...和康斯特·
- 阿姆斯特朗数字打印错误
- 阿姆斯特朗数字的代码不起作用
- 带循环的阿姆斯特朗数 - c++
- 阿姆斯特朗C++号
- 没有输出,我已经编了一个程序去找所有阿姆斯壮没有.在100到1000之间
- 生成阿姆斯特朗数的简单c++代码
- 用c++查找阿姆斯特朗数