-1

I am (new to c++) trying to create a power function manually and came across the issue where if the power inputted is negative, the result is always being printed out as 0. I suspect that one of the variables might not be declared properly, can you help please

#include <iostream>

using namespace std;

int power;
float result = 1, base;

int firs();
void pow(int base, int power);

int main()
{
    firs();
    pow(base, power);

    return 0;
}

int firs()
{
    cout << "Enter a base input: ";
    cin >> base;

    cout << "Enter a power input: ";
    cin >> power;

    return base, power;
}

void pow(int base, int power)
{
    cout << "With a given base of " << base << " and a given power of " << power << endl;

    if (power > 0)
    {
        for (int i = 0; i < power; i++)
        {
            result = result*base;
        }

    cout << "The final answer is: " << result;

    }
    else if (power < 0)
    {
        for (int i = 0; i > power; i--)
        {
            result = result*(1/base);
        }

    cout << "The final answer is: " << result;
    }
    else
    {
        cout << "The final answer is: " << 1;
    }
}
  • 1
    @Tony Yes, comma operator (`,`) executes all statements from left to right, and returns the rightmost one. So `return base, power;` is exactly the same as `return power;` – Yksisarvinen May 30 '19 at 22:05
  • Don't know what sense does that make... – Tony May 30 '19 at 22:06
  • In C/C++ you can only return one value from a function. Or give back a struct or change values by references – B. Go May 30 '19 at 22:07
  • @Tony [more info here](https://en.cppreference.com/w/cpp/language/operator_other#Built-in_comma_operator) – Not a real meerkat May 30 '19 at 22:08
  • It takes me awhile to see that `base` definition in `pow` function is shadowing `base` definition at global scope. The former is `int` and the later is `float` – Amadeus May 30 '19 at 22:14

2 Answers2

0

The problem lies in the following code section:

    else if (power < 0)
    {
        for (int i = 0; i > power; i--)
        {
            result = result*(1/base);
        }
    }

When (1/base) is calculated, because both 1 and base are int, the result will also be casted into int, which is 0 (if base is greater than 1). You can avoid this by either defining base as float, using 1.0 instead of 1, or using explicit type casting:

    else if (power < 0)
    {
        for (int i = 0; i > power; i--)
        {
            result = result*(1/(float) base);
        }
    }

Also, return base, power only returns power.

Xiaoyi Cao
  • 156
  • 6
0

Just change this line

        result = result*(1/base);

to

        result = result*(1.0/base);

And you will get the correct result.

Tony
  • 632
  • 1
  • 4
  • 18