Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

How to stop rounding decimals with double in c

I know this problem has been on the internet for a while but i cant seem to find how to stop my program from rounding the 3rd decimal.

the answer output is 4524.370 and should be 4524.369

also, i know my equations are stupid and could be simplified but im lazy

//Tanner Oelke CSE155E

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

 int main(void){

    double v, t; //base variables
    double sq1, sq2; //calculation variable for square root

    printf("Please enter the given air temperature in Fahrenheit:");
    scanf("%lf", &t);

    //unessecary equations but it works
    sq1=(57*t+297);
    sq2=(sq1/247);
    v=1086*sqrt(sq2);

    printf("%.3lf
", v);

    return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

With an input of "70.0" the result is 4524.369754... which displays as "4524.370" - What OP gets.

With an input of "69.999975" the result is 4524.369002... which displays as "4524.369" - what OP wants.

If OP expects "70.0" to result in "4524.369", then some minor adjustment to the formula is needed. The precision of double is at least 10 significant digits and often is 15+. Even doing this in float then f(70.0)--> 4524.370.

Else OP has the wrong expectation.


Response to OP's comment:

"to shorten the decimal place to 3 spots without rounding". Hmmm seems strange to want this:

// properly rounded result    
printf("%.3lf
", v);
// shorten to 3 places without rounding
double v3 = floor(v*1000.0)/1000.0;
printf("%.3lf
", v3);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...