问题描述
问题-在任意两个数字之间打印阿姆斯特朗数
在 VS 代码中编译
我是 C++ 的初学者。我正在创建一个 armstrong 数字程序来识别任何两个范围之间的数字。但是,代码在打印“100”后停止编译,这也是错误的输出。这是我需要审核的代码。
{int num1,num2,a,rem,result=0,n=0;
cout<<"Enter first number: ";
cin>>num1;
cout<<"Enter second number: ";
cin>>num2;
cout<<"Armstrong numbers between "<<num1<<" and "<<num2<<" are: "<<endl;
while (num1 != num2) //looping till first and last number becomes equal
{
//incrementing 'n' value to the number of digits in entered number
a=num1;
while (a != 0)
{
a/=10;
n++;
}
a=num1; //redefining a value to num1
while (a != 0) //looping to generate result
{
rem=a%10;
result+=pow(rem,n);
a/=10;
}
if (result==num1)
{
cout<<result<<endl;
}
else
{
continue;
}
n=0;
num1++;
}
return 0;}
解决方法
去掉else代码,无限循环当前数
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int num1,num2,a,rem,result = 0,n = 0;
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
cout << "Armstrong numbers between " << num1 << " and " << num2 << " are: " << endl;
while (num1 != num2) //looping till first and last number becomes equal
{
//incrementing 'n' value to the number of digits in entered number
a = num1;
while (a != 0)
{
a /= 10;
n++;
}
a = num1; //redefining a value to num1
while (a != 0) //looping to generate result
{
rem = a % 10;
result += pow(rem,n);
a /= 10;
}
if (result == num1)
{
cout << result << endl;
}
// you do not have to use else here.
// It will automatically continue with next line
n = 0;
a = 0;
result = 0;
num1++;
}
return 0;
}