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
810 views
in Technique[技术] by (71.8m points)

c - Getting float value from integers

How can I get a float or real value from integer division? For example:

double result = 30/233;

yields zero. I'd like the value with decimal places.

How can I then format so only two decimal places display when used with a string?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You could just add a decimal to either the numerator or the denominator:

double result = 30.0 / 233;
double result = 30 / 233.0;

Typecasting either of the two numbers also works.

As for the second part of the question, if you use printf-style format strings, you can do something like this:

sprintf(str, "result = %.2f", result);

Bascially, the ".2" represents how many digits to output after the decimal point.


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

...