针对Armstrong编号给出错误输出的C程序
问题描述:
该程序没有显示153作为Armstrong编号,而其他编号的输出正确。就像我检查407一样,它给出了正确的答案,但是当我检查153时,它显示的不是阿姆斯特朗数字。针对Armstrong编号给出错误输出的C程序
#include <stdio.h>
#include <math.h>
int main() {
int no, copy, re, n = 0, ans = 0;
printf("\n\tEnter a new number: ");
scanf("%d", &no);
copy = no;
while (copy != 0) {
copy = copy/10;
n++;
}
copy = no;
while (copy != 0) {
re = copy % 10;
ans = ans + pow(re, n);
copy = copy/10;
}
if (ans == no) {
printf("\n\t %d is an Armstrong number", no);
} else {
printf("\n\t %d is not an Armstrong number", no);
}
getch();
return 0;
}
答
首先你需要为变量
给予适当的名称试试这个代码我的作品
#include <stdio.h>
#include <math.h>
int main()
{
int number, originalNumber, remainder, result = 0, n = 0 ;
printf("Enter an integer: ");
scanf("%d", &number);
originalNumber = number;
while (originalNumber != 0)
{
originalNumber /= 10;
++n;
}
originalNumber = number;
while (originalNumber != 0)
{
remainder = originalNumber%10;
result += pow(remainder, n);
originalNumber /= 10;
}
if(result == number)
printf("%d is an Armstrong number.", number);
else
printf("%d is not an Armstrong number.", number);
return 0;
}
在这个程序中,number of digits of an integer
计算第一和存储在n
变量。
并且pow()
函数用于计算循环的每次迭代中个体数字的功率。
答
您的代码没有问题。它工作正常。编译您的代码gcc -o file filename.c -lm
并运行为./file
以避免连接问题。
答
你的算法是正确的,你的程序作为预期我的系统上执行(除了缺少换行符)。如果您的系统报告为而不是是阿姆斯壮编号,则可能是因为将数字提高到第n个功率的浮点操作而被打破。试试这个选择:
#include <stdio.h>
#include <math.h>
int main() {
int no, copy, re, i, d, n = 0, ans = 0;
printf("Enter a new number: ");
if (scanf("%d", &no) == 1) {
copy = no;
while (copy != 0) {
copy = copy/10;
n++;
}
copy = no;
while (copy != 0) {
d = copy % 10;
for (re = d, i = 1; i < n; i++) {
re *= d;
}
ans = ans + re;
copy = copy/10;
}
if (ans == no) {
printf("%d is an Armstrong number\n", no);
} else {
printf("%d is not an Armstrong number\n", no);
}
getch();
}
return 0;
}
你是否在调试器中逐行扫描你的代码?这是调试这些问题的正确方法,只有在尽力调试自己之后才能找到其他人的帮助。 – kaylum
你的代码显示了我给Armstrong的任何号码。 – Marievi
1)缩进代码2)正确命名你的变量。 –