C++程式顯示兩個區間之間的阿姆斯特朗數
阿姆斯特朗數是指其各位數字的立方和等於該數本身的數。
以下是一些阿姆斯特朗數的示例:
3 = 3^1 153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153 407 = 4^3 + 0^3 + 7^3 = 64 +0 + 343 = 407 1634 = 1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634
顯示兩個區間之間的阿姆斯特朗數的程式如下所示。
示例
#include <iostream> #include <cmath> using namespace std; int main() { int lowerbound, upperbound, digitSum, temp, remainderNum, digitNum ; lowerbound = 100; upperbound = 500; cout<<"Armstrong Numbers between "<<lowerbound<<" and "<<upperbound<<" are: "; for(int num = lowerbound; num <= upperbound; num++) { temp = num; digitNum = 0; while (temp != 0) { digitNum++; temp = temp/10; } temp = num; digitSum = 0; while (temp != 0) { remainderNum = temp%10; digitSum = digitSum + pow(remainderNum, digitNum); temp = temp/10; } if (num == digitSum) cout<<num<<" "; } return 0; }
輸出
Armstrong Numbers between 100 and 500 are: 153 370 371 407
在上面的程式中,找到了給定區間內的阿姆斯特朗數。這是透過多個步驟完成的。給出了區間的下限和上限。使用這些,從下限到上限啟動一個for迴圈,並評估每個數字以檢視它是否為阿姆斯特朗數。
這可以在以下程式碼片段中看到。
lowerbound = 100; upperbound = 500; cout<<"Armstrong Numbers between "<<lowerbound<<" and "<<upperbound<<" are: "; for(int num = lowerbound; num <= upperbound; num++)
在for迴圈中,首先找到數字(即num)中的位數。這可以透過為每個數字將digitNum加1來完成。
以下程式碼片段演示了這一點。
temp = num; digitNum = 0; while (temp != 0) { digitNum++; temp = temp/10; }
知道位數後,透過將每個數字的digitNum次冪(即位數)相加來計算digitSum。
這可以在以下程式碼片段中看到。
temp = num; digitSum = 0; while (temp != 0) { remainderNum = temp%10; digitSum = digitSum + pow(remainderNum, digitNum); temp = temp/10; }
如果數字等於digitSum,則該數字為阿姆斯特朗數並將其打印出來。如果不是,則它不是阿姆斯特朗數。這在下面的程式碼片段中可以看到。
if (num == digitSum) cout<<num<<" ";
廣告