0

Using GCC on the Ubuntu Linux 10.04, I have unwanted rounding after a division.

I tried:

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

void FormatReading(int temp)
{
    double reading = temp / 100;
    printf("%f\n",reading);  /* displays 226.000000, was expecting 226.60 */
}

int main(void)
{
    FormatReading(22660);
    return 0;
}

It was suggested to me to try:

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

void FormatReading(int temp)
{
    long reading = temp ;
    reading = reading / 100;
    printf("%3.2ld\n",reading);  /* displays 226 */
}

int main(void)
{
    FormatReading(22660);
    return 0;
}

I also tried:

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

void FormatReading(int temp)
{
    long reading = temp ;
    double reading2 = reading / 100;
    printf("%3.2f\n",reading2);  /* displays 226.00 */
}

int main(void)
{
    FormatReading(22660);
    return 0;
}

I also tried the round function using include math.h with compiler tag -lm in various ways, but did not find what I was looking for.

Any help greatly appreciated.

Best regards, Bert

Victor Zamanian
  • 3,100
  • 24
  • 31
quadmore
  • 69
  • 1
  • 3
  • 1
    possible duplicate of [What is the behavior of integer division in C?](http://stackoverflow.com/questions/3602827/what-is-the-behavior-of-integer-division-in-c) – Steve Jessop Apr 08 '11 at 12:55
  • Not a duplicate, @Steve. I don't think the OP knows that he is doing integer division. I think he thinks that `d = i/i` does floating-point division. – Robᵩ Apr 08 '11 at 19:48
  • @Rob: feel free to select any of the numerous other questions on the exact same point as a better duplicate. I think I just picked the first that looked to me like a close match, admittedly "looks to me" was influenced by the fact that I know the answer. If the questioner didn't realise he was doing integer division, then he does now :-) – Steve Jessop Apr 09 '11 at 20:24

2 Answers2

9
double reading = temp / 100.0;
                           ^^

temp / 100 is an integer division - that you assign the result to a double doesn't change this.

Erik
  • 88,732
  • 13
  • 198
  • 189
3

You are using integer division which always gives integral results rather than fractions, and then the result is being assigned to a double. Divide by 100.0 instead of 100 to get the behavior you want.

I82Much
  • 26,901
  • 13
  • 88
  • 119