【问题标题】:Writing a exponent function Without POW or Multiplication在没有 POW 或乘法的情况下编写指数函数
【发布时间】:2019-03-27 20:43:01
【问题描述】:

我正在尝试编写一个函数,该函数接受两个输入参数并计算将第一个输入的值提升到第二个输入的值的结果,然后返回结果。不允许使用乘法运算符 (*) 执行乘法运算,也不允许使用任何直接产生幂运算结果的内置 C++ 功能。

数据类型:当输入为正数、零或一,以及第二个输入为负数时,函数都能正常工作。我的回报总是 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;
}

【问题讨论】:

  • 你实现了乘法,而不是求幂。
  • 你有一个乘法函数,现在用它来做一个指数函数。
  • a*4 = a+a+a+a; a^4 = a*a*a*a; 用 N 替换 4 就可以了
  • 如果b == 0,您还应该记住特殊情况下的返回值
  • 也是 a 和 b 等于 0 的特殊情况。我假设您希望它返回 1 在这种情况下 Sean Bright 的评论有效,但考虑到您可能希望它的最终实现根据上下文为 0 或 1,甚至可能未定义。

标签: c++ function exponent


【解决方案1】:

没错,您实现的是乘法而不是求幂,但每次都得到 0 的原因是您没有将函数调用的返回值存储在 value 变量中,而是每次都输出零。

【讨论】:

  • 值 = exp(num1, num2);
  • 几个月前我才开始使用 c++,所以当我输入 value = exp(num1, num2);我使用了未初始化的 num2 错误我也不知道特殊情况是什么以及它在我的代码中的位置
  • 我实现了乘法而不是求幂是什么意思?是在 for 循环中 for (int i = 0; i
  • 我发现我把这个值 = exp(num1, num2) 放在了错误的地方,并修复了 for 循环/函数定义 int exp(int a, int b) { int result = 0; for (int count = 0; count
猜你喜欢
  • 1970-01-01
  • 2021-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多