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

c - how to divide the float number into 2 or 3 pieces

So I just received my paper. its said if the input number is 0.001001001 (repeated) it's gonna print 0.001..., if it's 0.015015015, then 0.015... as a print, if the number is 998 its should be 0.998... my idea is to divide it into something like 2 pieces but im still cant figure its out. thanks

scanf("%f",&num1);
scanf("%f",&num2);
scanf("%f",&num3);

num1 = floor(1000*(num1/999))/1000;
num2 = floor(1000*(num2/999))/1000;
num3 = floor(1000*(num3/999))/1000;

printf("%.3f...
",num1);
printf("%.3f...
",num2);
printf("%.3f...
",num3);

input = 3 integers that divide to 999, the value is below 999

output = the result, if the result repeated (0.001001001) then its going to print out 0.001...

sample :

input = output

3 = 0.003...

10 = 0.010...

998 = 0.998...

Note: I tried it with the floor so i guess there's something error about my logic

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Since the value is below 999, 999 not included, just read the integer, and print it with 0.%03d...:

int num;

scanf("%d", &num);
printf("0.%03d...
", num);

The conversion specification %03d will print the given integer in base-10, with leading zeroes prepended so that it is at least 3 characters wide. For 3, it will print 003, for 10 it will print 010 and for 976 it will print 976.

What you specifically cannot do this with are floats. Floats in your computer are binary numbers and they cannot precisely produce decimal fractions... nor can they do infinite precision.


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

...