-3

This is one of my first programs in C, so please bear with me! I wrote this code to calculate a base number raised to another given number. I got no compilation errors, except when I run my code, nothing happens. What am I doing wrong?

Thank you!

#include <stdio.h>
#include <stdlib.h>

int expCalculator(int base, int exponent) {
    if (exponent == 0){
        return 1;
    }
    else if (exponent % 2) {
        return base * expCalculator(base, exponent - 1);
    }
    else {
        int temp = expCalculator(base, exponent / 2);
        return temp * temp;
    }
}

int main() {
    float base, answer;
    int exponent;
    int positiveBase;
    char buffer[10];

    positiveBase = 0;
    while (positiveBase == 0){
        printf("Enter a base number: ");
        scanf(" %f", &base);
        if (base > 0){
            positiveBase = 1;
            printf("Please enter an exponent value to raise the base to: ");
            scanf(" %d", &exponent);
            answer = expCalculator(base, abs(exponent));
            gcvt(base, 10, buffer);
            printf(buffer, " to the power of ", exponent, " is ", answer);
        }
        else {
          printf("Please enter a positive base! Try again.");
        }
    }
    return 0;
}
  • 4
    Can you elaborate on "nothing happens"? Also check the return value of `scanf`s – Tormund Giantsbane Oct 11 '18 at 19:33
  • If "nothing happens" is literally true, try running your program from command line (xterm, cmd.exe, terminal, whatever). You should at least see those prints.. – hyde Oct 11 '18 at 19:37
  • 2
    `printf(buffer, " to the power of ", exponent, " is ", answer);` -> `printf("%s to the power of %d is %f\n", buffer, exponent, answer);` – Tormund Giantsbane Oct 11 '18 at 19:38
  • Possibly need `fflush(stdout);` after printing the prompts. Some stdio libraries will autoflush stdout before reading stdin, but this is not guaranteed. –  Oct 11 '18 at 19:38
  • You just need to fix that `printf`, that's not how it works. Surprised you aren't getting compiler errors – Tormund Giantsbane Oct 11 '18 at 19:39
  • 1
    Compile with warnings, fix all of them, disable optimizations and run with debugging enabled. If after that, you still see an infinite loop, you are probably introducing wrong input into `scanf`, which is returning `0` and not advancing the stream. – Acorn Oct 11 '18 at 19:46
  • _Side note:_ In `main`, `base` is a `float`, but, in `expCalculator`, `base` is an `int` and the function returns an `int`. Is that what you want or should change the function to use `float` instead [or `double`]? – Craig Estey Oct 11 '18 at 19:53
  • Thanks for all the responses. To elaborate on "nothing happens", even after fixing the printf statement as many have suggested, if I run it in an IDE or in my terminal, there's nothing that shows up. No print statements, nothing. In the IDE it just says that the program is "running" until I stop the program. – Talon Zhu Oct 11 '18 at 20:05
  • @TalonZhu I updated my answer to address the missing output. – dbush Oct 11 '18 at 20:29
  • Several answers mention the incorrect `printf` format, which should certainly be corrected, but I'm skeptical that it would cause an infinite loop. Most likely it would just produce garbled output. – Keith Thompson Oct 11 '18 at 21:55
  • I just got around to copying and running your program. The real problem is that your description of what happens appears to be incorrect. You wrote that "nothing happens", but when I tried it it correctly prompted for input and then printed an incorrect result. There is no infinite loop. Based on the description, I assumed that the `printf` was incorrect but not the cause of the problem. In fact, fixing the `printf` call does correct the problem. (You said in a comment that nothing shows up; I don't know why that would be the case. It should at least show the prompts.) – Keith Thompson Oct 12 '18 at 19:21

4 Answers4

1

You're not printing the results correctly:

printf(buffer, " to the power of ", exponent, " is ", answer);

The first parameter to printf is a format string, and the following parameters are the values that fit the format string. The compiler won't throw any warnings in this case because the first argument is of the correct type and the rest are variable arguments.

Many compilers will check these parameters against the given format string, but that doesn't happen in this case because the format string isn't a string constant. The only thing that gets printed is buffer, which is base converted to a string.

What you want is:

printf("%.10f to the power of %d is %f\n", base, exponent, answer);

Note that this prints base directly using a format string, as the gcvt function is obsolete.

As for why you're not seeing anything in your terminal, it could be due to buffering. The prompt you print doesn't contain a newline, so the output buffer won't necessarily get flushed. You'll need to do so manually:

printf("Please enter an exponent value to raise the base to: ");
fflush(stdout);
dbush
  • 205,898
  • 23
  • 218
  • 273
  • 2
    Perhaps emphasize that the `printf` line compiles without error _despite_ being very wrong. – Tim Randall Oct 11 '18 at 19:59
  • Isn't there normally an automatic flush if you read from stdin after printing to stdout, when both are connected to the terminal? It's not usually necessary to flush after printing a prompt because of this. – Barmar Oct 11 '18 at 20:36
  • Hmm, apparently not: https://stackoverflow.com/questions/2123528/does-reading-from-stdin-flush-stdout I guess it's an extension provided by my implementation (LLVM). – Barmar Oct 11 '18 at 20:38
0

Replace your printf() function line with : printf("%3.2f to the power of %d is %3.2f", base, exponent, answer);

The reason is first you need to provide the format of the string and then the values in the further arguments. Refer to the following link for more detailed instruction. http://www.cplusplus.com/reference/cstdio/printf/

Rahul Vashishtha
  • 688
  • 6
  • 22
0

There are multiple problems in your code:

  • negative base values pose no problem, why refuse them?
  • you did not include the standard header files for the library functions used.
  • function expCalculator() should use floating point arithmetics, preferably double.
  • negative exponents should be handled, it is rather easy.
  • you should not use gcvt: this function is non standard and might not be supported on some systems. Instead use printf with an appropriate format string.
  • the output statement printf(buffer, " to the power of ", exponent, " is ", answer); is incorrect. You should instead use a format string and arguments as show below.

Here is a corrected version

#include <stdio.h>
#include <stdlib.h>

double expCalculator(double base, int exponent) {
    if (exponent < 0) {
        return 1 / expCalculator(base, -exponent);
    } else
    if (exponent == 0) {
        return 1;
    } else
    if (exponent % 2) {
        return base * expCalculator(base, exponent - 1);
    } else {
        double temp = expCalculator(base, exponent / 2);
        return temp * temp;
    }
}

int main() {
    double base, answer;
    int exponent;
    int positiveBase;

    positiveBase = 0;
    while (positiveBase == 0) {
        printf("Enter a base number: ");
        scanf("%lf", &base);
        if (base > 0){
            positiveBase = 1;
            printf("Please enter an exponent value to raise the base to: ");
            scanf("%d", &exponent);
            answer = expCalculator(base, exponent);
            printf("%g to the power of %d is %g\n", base, exponent, answer);
        } else {
            printf("Please enter a positive base! Try again.\n");
        }
    }
    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
-1
  • I think the mistake in the code is the printf statement. The first argument to printf statement is a string which is the format specifier and then followed by the arguments.
  • You might have got confused on reading the manual of printf function's prototype
    int printf(const char *format, ...); as the first argument is const char* which doesn't mean you can pass the buffer which is not const
  • There is no need to convert the numbers into null terminated strings as printf has format specifiers like %f, %d, etc to take care of printing numbers.


#include <stdio.h>
#include <stdlib.h>

float expCalculator(float base, int exponent) {// Need to change the types to float
  if (exponent == 0) {
    return 1;
  } else if (exponent % 2) {
    return base * expCalculator(base, exponent - 1);
  } else {
    float temp = expCalculator(base, exponent / 2); // One more type change
    return temp * temp;
  }
}

int main() {
  float base, answer;
  int exponent;
  int positiveBase;
  //char buffer[10]; No need of a buffer

  positiveBase = 0;
  while (positiveBase == 0) {
    printf("Enter a base number: ");
    scanf("%f", &base);
    if (base > 0) {
      positiveBase = 1;
      printf("Please enter an exponent value to raise the base to: ");
      scanf("%d", &exponent);
      answer = expCalculator(base, abs(exponent));
      // Statement below is the major change you need to make
      printf("Base %f to the exponent %d = %f\n", base, exponent, answer);
    } else {
      printf("Please enter a positive base! Try again.");
    }
  }
  return 0;
}



Output:
Enter a base number: 2.3
Please enter an exponent value to raise the base to: 2
Base 2.300000 to the exponent 2 = 5.290000

shirish
  • 668
  • 4
  • 9
  • 2
    It would help more if you'd explain how this fixes the problem. Most readers aren't going to study the original code and your version to see exactly how they differ. (Also, you didn't fix the incorrect format string in the `printf` call.) – Keith Thompson Oct 11 '18 at 19:48
  • If your answer is going to be helpful to future readers, you need to explain exactly how it solves the problem. I can't tell from your answer what was wrong the the OP's code. – Keith Thompson Oct 11 '18 at 20:02