-1

There must be some egregious mistake I'm guilty of but I'm calculating the result of 2880 * 12 / 512 in C and even though I'm saving the result in a double variable it just doesn't save the remainder. According to Google and any other calculator 2880 * 12 / 512 = 67.5 however according to the program below it's 67.00. This is the code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <math.h>

int main() {
    double result;
    result = 2880 * 12 / 512;
    printf("result = %f\n", result);
    return 0;
}

I'm compiling the file called test.c which contains the code as: gcc test.c -o test -lm.

What am I doing wrong?

Yos
  • 1,276
  • 1
  • 20
  • 40

2 Answers2

2

Type cast your integer literal value. Like this.

result = (double)2880 * 12 / 512;

C11 standard:

6.5.5 Multiplicative operators

6 When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded.88) If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.

msc
  • 33,420
  • 29
  • 119
  • 214
  • Advanced corner concern: `(double) some_integer` forces a conversion to `double`. Had _some_integer_ been a large 60-bit number, that conversion may incurred rounding. By nudging to `double` math with `1.0*some_integer` instead of a cast, and when FLT_EVAL_METHOD==2, the conversion may proceed using `long double` math and form a more accurate answer. – chux - Reinstate Monica Jan 08 '18 at 16:08
2

2880 * 12 / 512 is all an integer expression and evaluates to an integer. After the fact it is assigned to a double variable, but then the precision is lost. You need to cast to a double so it evaluates to a double.

result = (double)2880 * 12 / 512;

or alternatively append a decimal point to tell the compiler that it is a floating point number:

result = 2880. * 12 / 512;
mdatsev
  • 3,054
  • 13
  • 28