Reputation: 61
I'm trying to print out Armstrong Numbers from 1-10000, and my question is that there are "four 1s" when i compile and run, and I would like to ask which part of coding that I did wrong, and what part of code should be revised if I want only one 1 to be printed out. Other than that, all the others Armstrong Numbers output correctly. It's my first time asking here and I hope people who sees this would give me some advice. Thank you.
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
printf("Armstrong Numbers from 1-10000:\n");
int digit1, digit2, digit3, digit4;
int i;
for(i=1; i<10000; i++){
digit4=i/1000;
digit3=(i%1000)/100;
digit2=((i%1000)%100)/10;
digit1=((i%1000)%100)%10;
//one digit number
if(i<10){
if(i==digit1)printf("%d\n",i);
}
//two digit number
if(10<=i<100){
int output100 = digit1*digit1 + digit2*digit2;
if(i==output100)printf("%d\n",i);
}
//three digit number
if(100<=i<=999){
int output1000 = digit1*digit1*digit1 + digit2*digit2*digit2 + digit3*digit3*digit3;
if(i==output1000){
printf("%d\n",i);
}
}
//four digit number
if(1000<=i<=10000){
int output10000 = digit1*digit1*digit1*digit1 + digit2*digit2*digit2*digit2 + digit3*digit3*digit3*digit3 + digit4*digit4*digit4*digit4;
if(i==output10000){
printf("%d\n",i);
}
}
}
return 0;
}
Upvotes: 0
Views: 2012
Reputation: 41027
Compile with warnings:
if(1000<=i<=10000){
warning: comparisons like ‘X<=Y<=Z’ do not have their mathematical meaning [-Wparentheses]
Do you mean if(i >= 1000 && i < 10000){
?
Upvotes: 8