C程序 显示两个区间的阿姆斯特朗数字
为了显示两个区间的阿姆斯特朗数字,我们可以使用2种不同的方法,即4种方法。
1.不使用pow()函数
2.使用pow()函数
我们将在上述所有方法中保持相同的输入,并得到相应的输出。
输入:
start = 1, end = 500
输出:
1
153
370
371
407
解释: 阿姆斯特朗数字是其数字的立方体之和。
i.e. 1=13
153= 13 + 53 + 33
370= 33 + 73 + 03 etc.
方法1:不使用pow()函数
办法A
// C program to demonstrate an armstrong number
// between the given intervals
#include <stdio.h>
int main()
{
int s = 1, e = 500, num, n, arm = 0, i, sum;
// iterating the for loop
// using the given intervals
for (i = s; i <= e; i++) {
num = i;
sum = i;
// finding the armstrong number
while (num != 0) {
n = num % 10;
arm = arm + (n * n * n);
num = num / 10;
}
// if number is equal to
// the arm then it is a
// armstrong number
if (sum == arm) {
printf("%d\n", i);
}
arm = 0;
}
return 0;
}
输出
1
153
370
371
407
办法B
// C program to demonstrate an armstrong number
// between the given intervals
#include <stdio.h>
int main()
{
int s = 1, e = 500, num1, n, arm = 0, i, num2, c;
// iterating the for loop using the given intervals
for (i = s; i <= e; i++) {
num1 = i;
num2 = i;
// finding the number of digits
while (num1 != 0) {
num1 = num1 / 10;
++c;
}
// finding the armstrong number
while (num2 != 0) {
n = num2 % 10;
arm = arm + (n * n * n);
num2 = num2 / 10;
}
// if number is equal to the arm then it is a
// armstrong number
if (arm == i) {
printf("%d\n", i);
}
arm = 0;
c = 0;
}
return 0;
}
输出
1
153
370
371
407
方法2:使用pow()函数
办法A
// C program to demonstrate an armstrong number
// between the given intervals using pow()
#include <math.h>
#include <stdio.h>
int main()
{
int s = 1, e = 500, num, n, arm = 0, i, sum;
// iterating the for loop using the given intervals
for (i = s; i <= e; i++) {
num = i;
sum = i;
// finding the armstrong number
while (num != 0) {
n = num % 10;
arm = arm + pow(n, 3);
num = num / 10;
}
// if number is equal to the arm then it is a
// armstrong number
if (sum == arm) {
printf("%d\n", i);
}
arm = 0;
}
return 0;
}
输出
1
153
370
371
407
办法B
// C program to demonstrate an armstrong number
// between the given intervals using pow()
#include <math.h>
#include <stdio.h>
int main()
{
int s = 1, e = 500, num1, n, arm = 0, i, num2, c;
// iterating the for loop using the given intervals
for (i = s; i <= e; i++) {
num1 = i;
num2 = i;
// finding the number of digits
while (num1 != 0) {
num1 = num1 / 10;
++c;
}
// finding the armstrong number
while (num2 != 0) {
n = num2 % 10;
arm = arm + pow(n, 3);
num2 = num2 / 10;
}
// if number is equal to the arm then it is a
// armstrong number
if (arm == i) {
printf("%d\n", i);
}
arm = 0;
c = 0;
}
return 0;
}
输出
1
153
370
371
407