2017-09-02 77 views
-1

我想在C++中编写一个函数,该函数可以识别并打印从一个位置到一个用户指定位置的范围内的Armstrong数字。它还会返回多少个整数。它读取的最大数量是9,999。Armstrong号码打印错误

我遇到的问题是它承认每个Armstrong数字都高达8208,但不是9474,它们都是Armstrong数字。这给我带来了很大的困惑,因为我根据数字的数量来处理数字,所以如果它能成功识别8208,它也应该识别9474.它不会。

这里是我的代码:

int isArmstrongNum(int range){ 
    int count = 0; 
    int ones; 
    int tens; 
    int hundreds; 
    int thousands; 
    if(range < 1 || range > 9999){ 
     cout << "invalid entry" << endl; 
     return 0; 
    } 
    for(int i = 1; i < range; i++){ 
     if(i < 10){ 
      if(pow(i, 1) == i){ 
       count++; 
       cout << i << endl; 
      } 
     } 
     else if(i > 9 && i < 100){ 
      ones = i % 10; 
      tens = (i - ones)/10; 
      if(pow(ones,2) + pow(tens,2) == i){ 
       count++; 
       cout << i << endl; 
      } 
     } 
     else if(i > 99 && i < 1000){ 
      ones = i % 10; 
      tens = ((i % 100) - ones)/10; 
      hundreds = (i - tens * 10 - ones)/100; 
      if(pow(ones,3) + pow(tens, 3) + pow(hundreds,3) == i){ 
       count++; 
       cout << i << endl; 
      } 
     } 
     else if(i > 999 && i < 10000){ 
      ones = i % 10; 
      tens = ((i % 100) - ones)/10; 
      hundreds = ((i % 1000) - tens*10 - ones)/100; 
      thousands = (i - hundreds * 100 - tens * 10 - ones)/1000; 
      if(pow(ones,4) + pow(tens, 4) + pow(hundreds, 4) + 
pow(thousands, 4) == i){ 
       count++; 
       cout << i << endl; 
      } 
     } 

    } 
    return count; 

}

任何想法,为什么它的行为这样?谢谢。

+0

如果你被要求找到阿姆斯特朗数字直到1000000,你还会创建那么多的变量和条件语句吗?我建议你应该首先概括你的程序。 – Ishpreet

+0

不要使用'pow'来整形一个整数 - 使用'x * x'。对于其他小整数幂同样如此。 –

+0

你应该重新命名该函数,因为它有点误导... – pmaxim98

回答

-1

希望这有助于!

#include <iostream> 
#include <cmath> 
using namespace std; 

bool is_armstrong(int number) 
{ 
    int length=0,n=number,temp=0; 
    while(n>0) 
    { 
     length++; 
     n/=10; 
    } 
    n=number; 
    while(n>0) 
    { 
     temp+=pow(n%10,length); 
     n/=10; 
    } 
    if(temp==number) 
     return true; 
    return false; 
} 

int main() 
{ 
    int i,start_range=1,end_range=9999; 
    for(i=start_range;i<=end_range;i++) 
    { 
     if(is_armstrong(i)) 
      cout<<i<<endl; 
    } 
    return 0; 
} 

Output: 
1 
2 
3 
4 
5 
6 
7 
8 
9 
153 
370 
371 
407 
1634 
8208 
9474 
+1

请解释*为什么*这段代码会有帮助?为什么不同? –

+0

@ThomasMatthews由于您不必为每个数字创建一个条件语句,比如一百或几千个。 – Ishpreet

+1

当您发布代码作为答案时,请注释您的代码和答案。 –