dot-combubble
dot-combubble

Reputation: 45

How to use fractions in C?

I am learning C now in DevC++ and I need to solve a simple exercise where a number (int or float, which is 10 in this case) is multiplied by a rate, which is a fraction (1/6 in this case). The output I get is 0.000000 when I run my code below, which is not correct. This works correctly on some fractions, such as 4/2.

What am I doing wrong? Please note: I cannot use some advanced solutions and functions because we haven't studied those. Also I have to use constants as part of the exercise because the fraction is already known at the start of the exercise. My code needs to be as simple as the one I am using now:

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

const float a = 10;
const float b = 1/6;
float c;

main()
{
   
   c = a * b;

   printf("Answer = %f", c);

   return 0;
}

Upvotes: 1

Views: 14795

Answers (4)

Luis Colorado
Luis Colorado

Reputation: 12688

You need to use floating point numbers, like 1.0 (and not 1, which happens to be integer) or 6.0 (and not 6, which is also an integer)

When you apply the division operator / to two integers, it does integer division which means the result should be an integer.

If you divide the integer 1 by 6, you get 0, and a remainder of 1.

The best you can do is using floating point literals when you want floating point expressions, like:

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

const float a = 10.0;    /* this time everything is double */
const float b = 1.0/6.0; /* you convert it into float on initialization */
float c;

main()
{
   
   c = a * b;            /* ... or when assigning */

   printf("Answer = %f", c);

   return 0;
}

and your program will work fine.

Upvotes: 0

whiskeyo
whiskeyo

Reputation: 914

You perform division on two constant integers, which are 1 and 6, and the result of such operation is equal to 0 and that value is being passed to float. Change the value of b to const float b = 1.0 / 6.0;.

Upvotes: 0

0___________
0___________

Reputation: 67638

const float b = 1/6;

1/6 is the integer division and it is equal 0

You need to use float constants:

const float b = 1.0f/6.0f;

The constants with suffix f have float type (1.0f, 5.12f). Without the suffix have double type (1.0, 5.12)

Upvotes: 3

dbush
dbush

Reputation: 224207

The constants 1 and 6 are both integers, so 1/6 performs integer division. If you want floating point division one or both values should be floating point constants:

const float b = 1.0/6.0;

Upvotes: 2

Related Questions