简单的 C++生成阿姆斯特朗数的代码
以下是我生成阿姆斯特朗数字的简单尝试。但它只输出“1”。可能出了什么问题?
#include<stdio.h>
#include<conio.h>
#include<iostream.h>
int main()
{
clrscr();
int r;
long int num = 0, i, sum = 0, temp;
cout << "Enter the maximum limit to generate Armstrong number ";
cin >> num;
cout << "Following armstrong numbers are found from 1 to " << num << "\t \n";
for(i=1;i<=num;i++)
{
temp = i;
while( temp != 0 )
{
r = temp%10;
sum = sum + r*r*r;
temp = temp / 10;
}
if ( i == sum ) {
cout << i;
sum = 0;
}
}
getch();
return 0;
}
The following is my simple attempt at generating Armstrong numbers. But it only outputs "1". What might be wrong?
#include<stdio.h>
#include<conio.h>
#include<iostream.h>
int main()
{
clrscr();
int r;
long int num = 0, i, sum = 0, temp;
cout << "Enter the maximum limit to generate Armstrong number ";
cin >> num;
cout << "Following armstrong numbers are found from 1 to " << num << "\t \n";
for(i=1;i<=num;i++)
{
temp = i;
while( temp != 0 )
{
r = temp%10;
sum = sum + r*r*r;
temp = temp / 10;
}
if ( i == sum ) {
cout << i;
sum = 0;
}
}
getch();
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您需要始终在 for-i-loop 内设置
sum = 0
。You need to always set
sum = 0
inside the for-i-loop.从你的代码来看
'r*r*r' 不是数字的 n 次方。
From your code
'r*r*r' isn't n'th power of the number.
首先,您假设 n(如 n 次方)始终为 3(在您的
r*r*r
中)。仅当您的初始值具有三位数时(如 153 示例),这才是正确的。您需要计算初始数字中的位数来计算 n,然后将您的
r*r*r
替换为 r 的 n 次方。但这并不能解释为什么没有找到 153。原因是您不会将
sum
重置为零除非找到匹配项。无论是否找到匹配项,您都需要将其重置为零。The first thing is that you're assuming that n (as in the nth power) is always three (in your
r*r*r
). That's only true if your initial value has three digits (as with the 153 example).You need to count the digits in your initial number to calculate n, and then replace your
r*r*r
with raising r to the nth power.This doesn't explain why 153 isn't found, though. The reason for that is because you aren't reseting
sum
to zero unless you find a match. You need to reset it to zero whether you found a match or not.您可以使用 log 计算 n:
然后正确计算
r^n
并在求和中使用它:sum += r^n;
。 r*r*r 不是计算它的正确方法。you can calculate n using log:
then calculate
r^n
correctly and use it in your summation:sum += r^n;
. r*r*r is not the correct way of calculating it.您的代码仅适用于
n=3
:sum = sum + r*r*r;
您必须使用
pow()
函数 (< a href="http://www.codecogs.com/reference/c/math.h/pow.php" rel="nofollow">http://www.codecogs.com/reference/c/math.h/ pow.php)来计算能力。 (或者创建一个自定义的。)Your code only works with
n=3
:sum = sum + r*r*r;
You must use the
pow()
function (http://www.codecogs.com/reference/c/math.h/pow.php) to compute powers. (Or create a custom one.)总结一下正确但部分的答案:
To summarize the right, but partial answers:
@Power-inside,我看到了你的代码,很难更改你的代码并编辑它,但我编写了一个类似的代码来在给定的限制内生成阿姆斯特朗数字,并且它工作得很好。
这里是....
@Power-inside, I saw your code, its difficult to change your code and edit it, but I have written a similar code to generate Armstrong numbers in a given limit, and it works fine.
Here it is....