I have this program to generate armstrong numbers upto a given range. But the problem is that the range variable (n in this case) is somehow acting like a const. I cannot assign a value nor increment it... There are errors during compilation with gcc. The power function works fine (Same issue with pow() defind in math.h). I would like to know why this is happening to this code and the possible fix(es). Thank you
#include <stdio.h>
//#include <math.h>
int power(int a, int b) {
int c = 1;
for(int i = 0; i < b; i++) {
c *= a;
}
return c;
}
void main(void) {
int sum, y, temp;
printf("temp, y, sum, n\n");
for(int n = 1; n < 100; n++) {
temp = n;
printf("%d ", temp);
y = 0; // y to hold the number of digits of n
while (n > 0) {
n = n / 10;
y++;
}
printf("%d ", y);
n = temp;
sum = 0;
while(n > 0) {
sum += power((n % 10), y);
n = n / 10;
}
if (temp == sum) {
printf("%d ", sum);
}
printf("%d\n", n);
}
}
Output:
temp, y, sum, n
1 1 1 0
1 1 1 0
1 1 1 0
1 1 1 0
1 1 1 0
1 1 1 0
1 1 1 0
.
.
.
Are you not constantly dividing n by 10?
As n is an integer that starts as 1, and not a float, it would constantly set to 0.
Your second while(n > 0)
loop effectively sets n=0
within the outer for
loop. Did you want to use a second n = temp
?
before the last printf statement add: n = temp;
try you code like this:
#include <stdio.h>
//#include <math.h>
int power(int a, int b) {
int c = 1;
for(int i = 0; i < b; i++) {
c *= a;
}
return c;
}
void main(void) {
int sum, y, temp;
printf("temp, y, sum, n\n");
for(int n = 1; n < 100; n++) {
temp = n;
printf("%d ", temp);
y = 0; // y to hold the number of digits of n
while (n > 0) {
n = n / 10;
y++;
}
printf("%d ", y);
n = temp;
sum = 0;
while(n > 0) {
sum += power((n % 10), y);
n = n / 10;
}
if (temp == sum) {
printf("%d ", sum);
}
n = temp;
printf("%d\n", n);
}
}
It is because the value of n is set to 0 outside the loop. Try the below code.
#include <stdio.h>
//#include <math.h>
int power(int a, int b) {
int c = 1;
for(int i = 0; i < b; i++) {
c *= a;
}
return c;
}
void main(void) {
int sum, y, temp;
printf("temp, y, sum, n\n");
for(int n = 1; n < 100; n++) {
temp = n;
printf("%d ", temp);
y = 0; // y to hold the number of digits of n
while (n > 0) {
n = n / 10;
y++;
}
printf("%d ", y);
n = temp;
sum = 0;
while(n > 0) {
sum += power((n % 10), y);
n = n / 10;
}
if (temp == sum) {
printf("%d ", sum);
}
n = temp;
printf("%d\n", n);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.