Waypoint
Waypoint

Reputation: 17783

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;
printf("%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?

Upvotes: 0

Views: 62112

Answers (4)

Brian Driscoll
Brian Driscoll

Reputation: 19635

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);

Upvotes: 1

Stephen Canon
Stephen Canon

Reputation: 106317

I believe you want:

piece = (b - a)/d;

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

Upvotes: 1

Vamana
Vamana

Reputation: 578

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;

Upvotes: 6

Sjoerd
Sjoerd

Reputation: 75679

Use parenthesis:

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

Upvotes: 5

Related Questions