0

Consider the following:

#include <stdio.h>

int main()
{
    int first=9;
    int second=0;
    double ratio;

    if(second==0)
        ratio="n/a";
    else
        ratio=(double)singularCount/pluralCount;

    printf("ratio is: %f", ratio);

    return 0;
}

This obviously wont run as it should.

How can I modify my code/print statement to print a float if there are no problems, and n/a if there is division by 0?

I will be printing many of these ratios in a list, so I'd like to see "n/a" when there is division by 0.

Desired Output:

ratio is: n/a
user3264405
  • 330
  • 1
  • 3
user3487243
  • 183
  • 1
  • 11

2 Answers2

1

You are doing something wrong...

you shouldn't put a string into a double variable.
What you want to do is to use isnan on undefined doubles (which are completely legit to hold), and have an if statement on it.

something like:

if (isinf(ration)) printf("ration is undefined\n");
else printf...

This way you can send the double and get it from methods/procedures/functions (that I urge you to use for code separation) and yet you'll be able to get different behaviors.

by the way - look at this code:

#include <stdio.h>
#include <math.h>
void main()
{
    double d = 1.0/0.0;
    if (isnan(d)) printf("it is n/a\n");
    else if (isinf(d)) printf("it is inf\n"); 
    else printf("%f\n",d);
}

another thing - %f in the case of inf or nan will just print the strings "inf" and "nan", if it's good enough for you - you don't need to change a thing, if it is for your eyes.

evenro
  • 2,626
  • 20
  • 35
  • You can still make this a single `printf` by allowing `NaN` to be printed. – legends2k Apr 02 '14 at 00:15
  • legends2k - I thought I wrote it at the end, but if not - it is actually important to emphasis it. dividing by 0.0 will not kill the program, and prating an undefined variable - will also not affect the application. it also means that we should be careful when using double and float because of it... – evenro Apr 02 '14 at 00:34
  • 1
    However, it should be noted that integer division by zero is undefined (would mostly lead to a crash) and doesn't have special values to represent states such as Inf, Nan, etc. – legends2k Apr 02 '14 at 04:07
0
if (second == 0) {
 printf("ratio is: n/a");
} else {
 printf("ratio is: %f", (double)singularCount/pluralCount);
}
Etheryte
  • 24,589
  • 11
  • 71
  • 116
  • That is one way I thought about, but I was trying to avoid having 2 print statements. Although ill use this solution, is there any other way? – user3487243 Apr 01 '14 at 23:53
  • @user3487243 You don't really want to worry about casting your floating-point output to a string (see http://stackoverflow.com/questions/7228438/convert-double-float-to-string), this is a better solution. – Etheryte Apr 02 '14 at 04:57