这是我的任务:
An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. For example, 153 is an Armstrong number since 1^3 + 5^3 + 3^3 = 153. Write a function named is_armstrong that takes one positive integer number as argument and returns a boolean variable which is true if the number is an Armstrong number and return false otherwise. Use this function is_armstrong in your main( ) function to print all Armstrong number in the range of 100 and 999
我写了一个程序,但它只打印出一个数字,999。谁能指出我的错误?非常感谢。
#include <iostream>
using namespace std;
//Function name: getRaiseAndAdd
//Purpose: Calculate each digit cubed and the sum of the results.
//We are sending in the current number from the loop starting at 100 and
//counting one by one to 999.
//Parameters: &numberInput
//Return value: Result of adding 3 numbers
int getRaiseAndAdd(int &numberInput)
{
int firstNumber, secondNumber, thirdNumber;
int remainder;
int sum;
int firstPower, secondPower, thirdPower;
firstNumber = numberInput / 100;
remainder = numberInput % 100;
secondNumber = remainder / 10;
thirdNumber = remainder % 10;
firstPower = firstNumber * firstNumber * firstNumber;
secondPower = secondNumber *secondNumber * secondNumber;
thirdPower = thirdNumber * thirdNumber * thirdNumber;
return sum = firstPower + secondPower + thirdPower;
}
int main()
{
int answer;
int originalNumber;
for(int i = 100; i < 1000; i++)
{
originalNumber = i;
answer = getRaiseAndAdd(i);
}
{
//Function name: is_Armstrong
//Purpose: finding the Armstrong numbers
//Parameters: answer
//Return value: 0
bool is_Armstrong (int answer);
if(answer == originalNumber);
{
cout<<"found an Armstrong number "<<originalNumber<<endl;
}
}
return 0;
}
最佳答案
您的代码有一些问题(不过您的 armstrong 函数似乎没问题)。首先,检查数字是否为 armstrong 数字的代码是在循环遍历所有内容后完成的。这需要在循环内完成,以便检查每个数字。
其次,在 if (if (answer == originalNumber); {...}
) 之后有一个分号。这导致执行无条件地落入下一个 block ,这就是它打印出 999 的原因(顺便说一句,这不是 armstrong 数字)。
因此修复方法是将您的检查移动到循环中并删除 if 之后的分号。
关于c++ - 为什么只打印一个阿姆斯特朗号码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36022908/