gpt4 book ai didi

c - 用 C 语言编写一个程序,打印 1 到 10000 之间的阿姆斯特朗数

转载 作者:行者123 更新时间:2023-11-30 20:11:40 25 4
gpt4 key购买 nike

这是我写的程序。当我执行它时,我得到一个空白输出。无法弄清楚它出了什么问题。

#include <stdio.h>
void main() {
int a, b = 0, s, n;
printf("The armstrong numbers are-");
for (n = 1; n <= 10000; n++) {
s = n;
while (n > 0) {
a = n % 10;
b = b + a * a * a;
n = n / 10;
}
if (b == s)
printf("%d ", s);
}
}

最佳答案

正如其他人建议的那样,不要更改 n在 for 循环内,因为循环取决于变量 n 。你必须设置b返回0对于每次迭代。

您的程序可读性不是很好,因为其他人可能不明白a的含义。 , b , ns意思是。因此,始终使用有意义的变量名称,如下所示:(有关更多说明,请参阅注释)

#include<stdio.h>  

int main(void) //correct signature for main function
{
int digit; //instead of a
int sum=0; //instead of b
int number; //instead of n

printf("The armstrong numbers are-");

for(number = 1; number <= 10000; number++)
{
int temporary = number; //temporary integer to store number value
sum = 0; //sum must be reset to 0 at the start of each iteration

while(temporary > 0)
{
digit = temporary % 10;
sum = sum + (digit * digit * digit);
temporary = temporary / 10;
}

if(sum == number) //if sum obtained == number, print it!
printf("%d ",number);
}

return 0;
}

输出:

The armstrong numbers are-1 153 370 371 407 

关于c - 用 C 语言编写一个程序,打印 1 到 10000 之间的阿姆斯特朗数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39951803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com