微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Armstrong 数字程序中的运行时错误

如何解决Armstrong 数字程序中的运行时错误

问题-在任意两个数字之间打印阿姆斯特朗数

错误-错误输出

在 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;
}


版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。