-3

I am making a calculator in c, everything works except when using the division command "/"

When a number is divided by 0 it should print out "NaN" and then exiting the program. However the output is: NaN0.0

Meaning that the function is also returning the value of the float despite using the return 0 command.

How do i make it so that the function just returns "NaN"?

float calc(float param1, char operator1, float param2){
#include <math.h>

float result;


switch(operator1){

        case '+':
                result = param1 + param2;
                return result;
break;

        case '-':
                result = param1 - param2;
                return result;
break;

        case '*':
                result = param1 * param2;
                return result;
break;

        case'/':
                if(param2 == 0){printf("NaN"); //Issue here
                return 0;
                }
                else{
        result = param1 / param2;}
        return result;
break;

        case '^':
        result = pow(param1, param2);
        return result;
}

}

 

1 Answers1

0

I'd need the full code to be able to be 100% certain, but I think what you are doing is the following:

printf('%lf', calc(0, '/', 0)); 

So, you're outputting the result of the execution of the "calc" command on screen, which is here: 0

But, before returning this 0 value, you're also printing the value "NaN" to screen.

So, by doing:

printf('%lf', calc(0, '/', 0)); 

You're telling the computer:

  • Compute the result of calc(0, '/', 0) : It prints NaN during the execution
  • Then, print the result, which is 0

That's why your computer is showing NaN 0

The function is not returning two values. It's indeed returning only one, but also printing NaN.

To fix that, just remove the print and return a special value that can be understood as NaN in the rest of your code.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Alexis Clarembeau
  • 2,776
  • 14
  • 27