[英]Printing Armstrong numbers in C
這是一個查找 1-1000 之間的阿姆斯特朗數的程序(數字的每個數字的立方數等於數字本身)。它正確打印了一些數字,但沒有打印 153。我的問題是為什么會這樣153被排除在外? 先感謝您。
#include<stdio.h>
#include<math.h>
void main()
{
int i,save,rem;
for(i=1;i<1000;i++)
{
int s=0;
int save=i; /*Creating copy of the
variable i.*/
while(save!=0)
{
rem=save%10;
save/=10;
s+=pow(rem,3.0);
}
if(i==s) //Comparing i with the sum.
printf("\n%d",i); //Printing armstrong number.
}
}
在pow上,在Windows 7上使用gcc。 但是,此代碼可能對您有用,以避免使用pow()舍入。
此代碼還簡化了循環並刪除了對save的重新聲明。
#include <stdio.h>
int main(void) {
int i, sum, ones, tens, hunds;
for(i = 1; i < 1000; i++) {
sum = i/10;
ones = i%10;
tens = sum%10;
hunds = sum/10;
sum = ones*ones*ones + tens*tens*tens + hunds*hunds*hunds;
if(i == sum)
printf("\n%d", i);
}
}
根據@Brij Raj Kishore的評論,如果該帖子確實打算顯示所有阿姆斯特朗數字1-1000,請用以下內容代替上面的循環。
for(i = 1; i < 1000; i++) {
sum = i/10;
ones = i%10;
tens = sum%10;
hunds = sum/10;
if(!(hunds | tens))
sum = ones;
else if (hunds == 0 && tens != 0)
sum = ones*ones + tens*tens;
else
sum = ones*ones*ones + tens*tens*tens + hunds*hunds*hunds;
if(i == sum)
printf("\n%d", i);
}
我已經在您的程序中做了一些修改,例如
打印1位數字,因為它們是阿姆斯壯數字,並且
避免了浮點數冪函數和其他小的更改,這些更改可以在代碼的注釋中看到。
#include<stdio.h>
#include<math.h>
void main()
{
int i,save,rem;
for(i=1; i<= 1000;i++)
{
int s=0;
int save=i; /*Creating copy of the variable i.*/
while(save!=0)
{
rem=save%10;
save/=10;
int temp = rem;
for(int j = 1; j < 3; ++j) { // power function
rem = rem * temp;
}
s+=rem;
}
if(i==s) //Comparing i with the sum.
printf("%d\n",i); //Printing armstrong number.
}
}
產量
1153370371407
編輯: 我已經根據OP定義的阿姆斯特朗編號進行了更改
#include <stdio.h>
main()
{
int n, temp, d1, d2, d3;
printf("Print all Armstrong numbers between 1 and 1000:\n");
n = 001;
while (n<= 900)
{
d1 = n - ((n / 10) * 10);
d2 = (n / 10) - ((n / 100) * 10);
d3 = (n / 100) - ((n / 1000) * 10);
temp = (d1 * d1 * d1) + (d2 * d2 * d2) + (d3 *
d3 * d3);
if (temp == n)
{
printf("\n Armstrong no is:%d", temp);
}
n++;
}
}
#include<stdio.h>
int main()
{
int n,r,sum=0,temp;
printf("enter the number=");
scanf("%d",&n);
temp=n;
while(n>0)
{
r=n%10;
sum=sum+(r*r*r);
n=n/10;
}
if(temp==sum)
printf("Armstrong number ");
else
printf("not Armstrong number");
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.