-1

Example (in C):

#include<stdio.h>

int main()
{
    int a, b = 999;
    float c = 0.0;
    scanf("%d", &a);
    c = (float)a/b; 
    printf("%.3lf...", c);
    return 0;
}

If I put 998 it will come out 0.999, but I want the result be 0.998; how?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Zefanya L
  • 9
  • 3
  • 4
    @Yksisarvinen - That "duplicate" is way, waay, waaay over(ab)used. – StoryTeller - Unslander Monica Oct 14 '18 at 11:00
  • Possible duplicate of [How to stop rounding decimals with double in c](https://stackoverflow.com/questions/32445882/how-to-stop-rounding-decimals-with-double-in-c) – πάντα ῥεῖ Oct 14 '18 at 11:00
  • 1
    `c = (int)(0.001+a*1000.0/b)/999.999;` – pmg Oct 14 '18 at 11:05
  • 2
    Possible duplicate of [How to round floating point numbers to the nearest integer in C?](https://stackoverflow.com/questions/2570934/how-to-round-floating-point-numbers-to-the-nearest-integer-in-c) – Intsab Haider Oct 14 '18 at 11:09
  • @Yksisarvinen: This question as stated has nothing to do with floating-point arithmetic. Proof: If the `float` and `double` types implemented perfect real-number arithmetic, the division would yield exactly .998998998…, and then formatting it to three decimal digits would produce “.999”. So the question is requesting a truncate-instead-of-round formatting, not a change to or fix for floating-point arithmetic. – Eric Postpischil Oct 14 '18 at 12:14
  • Side note: I would not use `%lf` to print a `float` value. (It works, but it's doubly misleading.) – Steve Summit Oct 14 '18 at 12:34

1 Answers1

2

It looks like you want to truncate instead of round.

The mathematical result of 999/998 is 0.9989989989... Rounded to three decimal places, that is 0.999. So if you use %.3f to print it, that's what you're going to get.

When you convert a floating-point number to integer in C, the fractional part is truncated. So if you had the number 998.9989989 and you converted it to an int, you'd get 998. So you can get the result you want by multiplying by 1000, truncating to an int, and dividing by 1000 again:

c = c * 1000;
c = (int)c;
c = c / 1000;

Or you could shorten that to

c = (int)(c * 1000) / 1000.;

This will work fine for problems such as 998/999 ≈ 0.998, but you're close to the edge of where type float's limited precision will start introducing its own rounding issues. Using double would be a better choice. (Type float's limited precision almost always introduces issues.)

Steve Summit
  • 45,437
  • 7
  • 70
  • 103
  • This is subject to rounding errors in the multiplication. One correct solution, if the C implementation provides correctly rounded conversions in the formatted I/O functions, is to `sprintf` to a buffer with enough digits to represent the exact value, then take only the desired first digits. – Eric Postpischil Oct 14 '18 at 12:19
  • @EricPostpischil Good point about the rounding. Answer updated. – Steve Summit Oct 14 '18 at 14:13