Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...