开发者

C - how to divide floats?

I get input from command line as a int d. Now I am facing this problem:

float a,b;
int d;
float piece;    
printf("Please enter the parts to divide the interval: ");
scanf("%d", &d);

a=0;
b=1;

piece=b-a/(float)d;
pri开发者_如何学运维ntf("%f\n",piece);

All I want is to printf some float number dependent on &d. e.g. when I write here 5, I would get 0.20000, for 6 - 0,166666 but I am still getting 1.000000 for all numbers, does anyone knows solution?


Division has precedence over subtraction, so you need to put the subtraction inside parentheses. You don't have to explicitly cast d to float; dividing a float by it will promote it to float.

piece = (b - a) / d;


Use parenthesis:

piece=(b-a)/(float)d;


I believe you want:

piece = (b - a)/d;

I.e., the problem isn't division, but order of operations.


I think this line: piece=b-a/(float)d;

should be: piece=(float)(b-a)/(float)d;

Just my 2 cents.

EDIT

Since d is an int, perhaps try this instead:

piece=(float)((b-a)/d);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜