[英]Writing a exponent function Without POW or Multiplication
Im trying to Write a function that accepts two input parameters and computes the result of raising the value of the first input to the value of the second input, and returns the result.我正在尝试编写一个函数,该函数接受两个输入参数并计算将第一个输入的值提高到第二个输入的值的结果,并返回结果。 You are not allowed to use the multiplication operator(*)for performing multiplication, nor are you allowed to use any built-in C++ functionality that directly produces the exponentiation result.不允许使用乘法运算符 (*) 执行乘法,也不允许使用任何直接生成求幂结果的内置 C++ 功能。
Data Types: function works correctly for both inputs being positives, zeroes, or ones, and when the second input is negative.数据类型:函数适用于正数、零或 1 的两个输入,以及当第二个输入为负时。 my return is always 0 what am I doing wrong我的回报总是 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 的原因是您没有将函数调用的返回值存储在 value 变量中,而是每次都输出零。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.