我想在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;
}
任何想法,爲什麼它的行爲這樣?謝謝。
如果你被要求找到阿姆斯特朗數字直到1000000,你還會創建那麼多的變量和條件語句嗎?我建議你應該首先概括你的程序。 – Ishpreet
不要使用'pow'來整形一個整數 - 使用'x * x'。對於其他小整數冪同樣如此。 –
你應該重新命名該函數,因爲它有點誤導... – pmaxim98