我试图编写一个接受两个输入参数的函数,并计算将第一个输入的值提高到第二个输入值的结果,并返回结果。不允许使用乘法运算符(*)执行乘法运算,也不允许使用任何直接产生取幂结果的内置C ++功能。
数据类型:函数对于正,零或1的输入都是正确的,当第二个输入为负时。我的回报永远是0,我做错了什么
#include <iostream>
using namespace std;
int exp(int, int);
int main()
{
int num1, // to store first number
num2, // to store second number
value = 0;
// read numbers
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
// call function
exp(num1, num2);
// print value
cout << "The value of " << num1 << " to the " << num2 << " is: " << value << endl << endl;
system("pause");
return 0;
}
// function definition
int exp(int a, int b)
{
int result = 0;
for (int i = 0; i < a; i++)
{
result += b;
}
return result;
}
是的,你正在实现乘法而不是取幂,但每次得到0的原因是你没有将函数调用的返回值存储在值变量中,而是每次都输出零。