At a candy shop the 1st candy costs l0cents Each sequent can

At a candy shop, the 1st candy costs l0cents. Each sequent candy costs 10 cents more than the previous one. For one dollar, how many candies can you purchase at most? Here is a program written in C to answer that question. float fundLeft = 1.0; float cost; int numCandies = 0; for(cost=0.1; cost

Solution

For comparison of float number in c use the precision as shown in the program.

Then it will give the correct output

{
float fundLeft=1.0;
float cost;
int numcandies = 0;
float precision = 0.00001;
for (cost=0.1;(cost - precision)<=fundLeft;cost +=0.1)
{
numcandies++;
fundLeft = fundLeft - cost;
}

}

printf(\"%d candies; %f leftover, \",numcandies,fundLeft);

output is :

3 candies; 0.400000 leftover.

This output is correct as

1st candy is purchased of 0.1 fund left 0.9

2nd candy is purchased of 0.2 fund left 0.7

3rd candy is purchased of 0.3 fund left 0.4

4th candy is purchased of 0.4 fund left 0 .

 At a candy shop, the 1st candy costs l0cents. Each sequent candy costs 10 cents more than the previous one. For one dollar, how many candies can you purchase a

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site