-2

I have to create a function that return the value of b^e. This is what I have done:

#include<stdio.h>
#include<math.h>

int funzione_potenza (int b, int e);

int main ()
{
    int b, e, potenza;

    printf("Inserisci la base: ");
    scanf("%d",&b);

    printf("Inserisci l'esponente: ");
    scanf("%d",&e);

    printf("La potenza e' %d",potenza);

    return 0;
}

int funzione_potenza (int b, int e)
{
    int potenza;

    potenza = pow(b,e);

    return potenza;
}

When i run it, it displays a false value of the power (ex. 5343123) What is wrong?

klutt
  • 30,332
  • 17
  • 55
  • 95
Teorema
  • 83
  • 6
  • 2
    What happens when you try it? – Fred Larson Nov 01 '17 at 14:08
  • 4
    I imagine that using `pow` is considered cheating – Chris Turner Nov 01 '17 at 14:08
  • Nothing happens if I run it because I have only to write a function and not the whole program (including main function etc.) – Teorema Nov 01 '17 at 14:10
  • 1
    Moreover it will give some pretty unexpected results for some numbers... – Eugene Sh. Nov 01 '17 at 14:10
  • @Teorema Then write the full program! Do you expect others to do it for you? – Eugene Sh. Nov 01 '17 at 14:10
  • 1
    `pow` returns a double, so probably not great to cast to an int. I'm supposing that this was a homework assignment, so it can go one of 2 ways. Either you'll be good because you learned that libraries exist, or you'll fail because you didn't learn how to think to resolve a code request. – AntonH Nov 01 '17 at 14:10
  • 1
    Welcome to stackoverflow.com. Please take some time to read [the help pages](http://stackoverflow.com/help), especially the sections named ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). Also please [take the tour](http://stackoverflow.com/tour) and [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask). Lastly please learn how to create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve). – Some programmer dude Nov 01 '17 at 14:12
  • https://stackoverflow.com/questions/29787310/does-pow-work-for-int-data-type-in-c – msc Nov 01 '17 at 14:12
  • "Is my code correct?" Not portable. `power = lrint(pow(b,e));` would work yet an integer only solution would be better. – chux - Reinstate Monica Nov 01 '17 at 14:13
  • 1
    Input values...? – Support Ukraine Nov 01 '17 at 14:18
  • 6
    You don't call the `funzione_potenza`. Therefore the content of the `potenza` variable is indeterminate. – Jabberwocky Nov 01 '17 at 14:19
  • Replace `potenza = pow(b,e);` with `double y = pow(b,e); potenza = y; printf(".20e %d\n", y, potenza);` to gain insight as to what is wrong. – chux - Reinstate Monica Nov 01 '17 at 14:20
  • @Teorema I suppose this is a homework (it's OK to ask questions about homework if you have difficulties with the code you have written). What is the exact requirement of the homework? – Jabberwocky Nov 01 '17 at 14:32
  • @Teorema however the answer I posted is may not be what your teacher expects. Maybe he wants you to create your own "power" function without callign the built-in `pow` function. – Jabberwocky Nov 01 '17 at 14:36

5 Answers5

2

You don't need a function to invoke the inbuilt pow function. If you are trying to write a function of your own, try to build a solution with loop or recursion.

sudha
  • 93
  • 2
  • 7
0

Assuming you are free to use math library, the method will return correct answer unless the number fits in "int". Otherwise, consider using "long long int" for larger numbers.

In case you are not allowed to use math library, here is a correct implementation:

long long int power(int b, int e){
          if(e==0){
                 return 1;
           }
           else if(e%2==1){
                 long long int temp = power(b,e/2);
                 return temp*temp*b;
           }
           else{
                 long long int temp = power(b,e/2);
                 return temp*temp;
           }
 }
0

There are two issues:

First of all you're getting a garbage value because you never call the funzione_potenza function.

int main()
{
  int b, e, potenza;

  printf("Inserisci la base: ");
  scanf("%d", &b);

  printf("Inserisci l'esponente: ");
  scanf("%d", &e);

  potenza = funzione_potenza(b, e);       // <<<<<<<<<< insert this line

  printf("La potenza e' %d", potenza);

  return 0;
}

Secondly you don't even need the funzione_potenza which is just a wrapper around pow, you can call pow directly:

...
scanf("%d", &e);

potenza = pow(b, e);

printf("La potenza e' %d", potenza);
...
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • I doubt their teacher would accept this as a valid answer to their homework though - they're meant to write their own version of `pow` – Chris Turner Nov 01 '17 at 14:29
  • 2
    @ChrisTurner maybe, but the OP didn't specify anything. And the main problem was the function not being called. – Jabberwocky Nov 01 '17 at 14:30
  • 1
    `pow(b, e);` returns a `double`. Many `pow()` implementations return a `double` that is not an exact mathematical correct result for integer arguments, yet only _very_ near it - and sometime just less. The assignment of a `double` to `int` truncates the fraction resulting in an off-by-one result. Not portable code and difficult to insure it is correct on a given platform. – chux - Reinstate Monica Nov 01 '17 at 14:47
0

you can implement power function without using "pow"usage of "pow"-function the built-in function as well below is the code.

#include <stdio.h>

//function prototype
int funzione_potenza (int b, int e);

int main ()
{
  int b, e, potenza;

  printf("Inserisci la base: ");
  scanf("%d",&b);

  printf("Inserisci l'esponente: ");
  scanf("%d",&e);

  potenza = funzione_potenza (b,e);

  printf("La potenza e' %d",potenza);

  return 0;
 }

 int funzione_potenza (int b, int e)
 {
    //local variables
    int i, potenza = b; //initialize potenza with b

    for (i = 0; i < e; i++ )
    {
       potenza = potenza * e; //multiply n-number of times to get the power
    } 

    return potenza;
 }
-1

My intention was to show the way you can realize that but that's basically reinventing the wheel so not recommended. Here I have shown the rough idea of how you can try to write a power function.

Alternative way to realize that would be

int mpow(int b, int e) {
    if (e <= -1) {
        fprintf(stderr, "mpow:(b: integer, e:non-negative integer )");
        exit(1);
    }
    if (e == 0) return 1;
    if (b == 0) return 0;
    int ans = 1;
    for (int i = 1; i <= e; i++) {
        if (!checkIfOverflown(ans, b)) ans = ans * b;
        else {
            fprintf(stderr, "%s\n", "overflow in multiplication");
            exit(1);
        }

    }
    return ans;

}

As pow returns double you shouldn't cast it to integer( why do you want to lose precision).

And why wrap pow in function? You can use it directly.

Is my function correct?

This function is correct as long as the integer doesn't mess it up by spilling up things. For small value of b,e it works.

Also a simple more effective way to do this will be

int mpow(int b, int e) {
    int res = 1, flag = 0;
    if (e <= -1) {
        fprintf(stderr, "mpow:(b: integer, e:non-negative integer )");
        exit(1);
    }
    while (e > 0) {
        if (e % 2 == 1) {
            if (!checkIfOverflown(res, b))
                res = (res * b);
            else {
                flag = 1;
                break;
            }
        }
        if (!checkIfOverflown(b, b))
            b = (b * b);
        else {
            flag = 1;
            break;
        }
        e /= 2;
    }
    if( flag ){
        fprintf(stderr, "%s\n", "overflow in multiplication");
        exit(1);
    }
    return res;
}
user2736738
  • 30,591
  • 5
  • 42
  • 56
  • Come on downvoter I expected a better one. Atleast give a review of what's wrong? :) – user2736738 Nov 01 '17 at 14:15
  • I don't want to get an upvote --but at least let me know what I am doing wrong? Is it my answering bothering someone? Or is it tecnical issue? Because I am saying the same thing as the other answers posted here. – user2736738 Nov 01 '17 at 14:21
  • NMDV, yet `pow(0, 1)` unnecessarily fails. Also solution is weak as it takes `e` iterations when a `log(e)` solution is easy to code. It unnecessarily uses `long`, when OP's goal is `int`. – chux - Reinstate Monica Nov 01 '17 at 14:25
  • @chux.: Yes ok..I was editing that..when I answer here I generally try to give the incremental approach to the solution...first simple to more complicated efficient. And yes...thanks for the support..I don't want to know the faults to get an upvote later....but if you downvote giving the user to modify his/her answer is a great thing. Thanks for that. I am always for changing my answer to make it better. – user2736738 Nov 01 '17 at 14:28
  • NMDV either but I can guess on a number of reasons. a) How should your code be "simpler than just `pow` ? b) You change function signature c) you change function name d) You don't handle `b` equal zero. – Support Ukraine Nov 01 '17 at 14:34
  • @4386427.: It's not simpler but the realization is much more easier. That exponentiation is nothing other than series of multiplication I will edit the line because yes it leads people to think what I didnt mean. – user2736738 Nov 01 '17 at 14:36
  • `pow(0,0)` is [often considered](http://www.askamathematician.com/2010/12/q-what-does-00-zero-raised-to-the-zeroth-power-equal-why-do-mathematicians-and-high-school-teachers-disagree/) `1` and not `0` like this code. – chux - Reinstate Monica Nov 01 '17 at 14:38
  • @coderredoc - I don't care how hard it is to implement the `pow`cause someone has already done that for me. So for me it is simpler to use `pow` than writing my own function ;-) There could be other reasons for writing my own function but to me "simpler" is not a reason – Support Ukraine Nov 01 '17 at 14:39
  • @4386427 Note that simplistic application of the `double` function `pow()` for integer math has [implementation concerns](https://stackoverflow.com/questions/47056768/create-a-function-that-return-the-pow-be/47056874?noredirect=1#comment81062247_47057172). – chux - Reinstate Monica Nov 01 '17 at 14:59
  • @chux.: That's why check my edit where I said that don't do that. – user2736738 Nov 01 '17 at 15:02
  • @chux.: Is there anything I can do to modify the answer regarding what you said? I have mentioned that point – user2736738 Nov 01 '17 at 15:13
  • @chux.: Would it be possible for you to comment on the answer? – user2736738 Nov 01 '17 at 15:26
  • coderredoc: My [comment](https://stackoverflow.com/questions/47056768/create-a-function-that-return-the-pow-be/47056874?noredirect=1#comment81062709_47056874) was to 4386427. Good to advise against direct use of `pow()`. Some `mpow()` concerns. 1) It is problematic when `b < -1`. (not that many care) 2) problem when `b == -1` due to `INT_MAX/b` overflow (again, not that many care) 3) The comment about OF with `res*b` also applies to `b*b`. – chux - Reinstate Monica Nov 01 '17 at 15:42
  • @chux.: 3) I have mentioned...in comment. It can always be checked via a function... .. – user2736738 Nov 01 '17 at 15:44
  • @chux.: I will modify the answer and let you know – user2736738 Nov 01 '17 at 16:06
  • Seems to work OK and reasonable efficient for many typical values although it does unnecessarily fail when `checkIfOverflown(b, b)` is true yet the loop did not need to perform that multiplication because the loop would have ended due to small `e`. It also reports `mpow(-1, -1) --> 1` when `-1` is expected. IMO, the exponent should be `unsigned` or the function specified to be UB with negative `e`. For a good review, consider https://codereview.stackexchange.com – chux - Reinstate Monica Nov 01 '17 at 19:03
  • @chux.: I can make the necessary changes now..you have given a great feedback – user2736738 Nov 01 '17 at 19:06
  • try `mpow(3,16), mpow(3,19)` For further review, create an account at codereview.stackexchange.com – chux - Reinstate Monica Nov 01 '17 at 19:19
  • @chux.: It will overflow...that;s why I should use the return type of `long`..the arguments to be long..to give a more high range..changing it to long will give a broader range. – user2736738 Nov 01 '17 at 19:21