简体   繁体   中英

Why doesn't my formula calculate a value in WHILE loop?

I'm trying to get the mid-calculating result for my piece of console code.
The task is the following:

There is a total of A tonnes of vegs in a warehouse.
In the end of a month 1 we take B tonnes to be sold, in the end of 2nd month - (1.1*B) , in the end of M month we take (1+(M-1)/10)*B tonnes. We have the limit of 10 months (we shall not calculate for more than 10 months).
The initial A and B values are typed in by the user.

My code:

float A,B; 
int M = 1; 
... /here user types stuff in/...

while (M<10)
    {
        B = (1 + (M - 1) / 10) * B; // goddamn formula that can't execute normally
        cout << "It's " << M << " month, we took " << B << " tonnes of vegs." << endl;
        M++;
    }

What I type in:
A = 500; B = 1

What I expect should happen:
It's 1 month, we took 1 tonnes of vegs.
silent calculations: B= (1+(1-1)/10)*1 = 1; M= 1+1 = 2
It's 2 month, we took 1.1 tonnes of vegs.
silent calculations: B= (1+(2-1)/10)*1 = 1.1; M= 2+1 = 3
It's 3 month, we took 1.32 tonnes of vegs.
silent calculations: B= (1+(3-1)/10)*1.1 = 1.32; M= 3+1 = 4
and so on until we reach the 10th month.

What I see instead:
It's 1 month, we took 1 tonnes of vegs
It's 2 month, we took 1 tonnes of vegs
It's 3 month, we took 1 tonnes of vegs
And so on, so the months are calculating but the formula from the task doesn't.

Whichever value of BI place instead is always being shown.

What am I doing wrong?

M is an int . So, (1 + (M - 1) / 10) is an int too. That division is integer division. You're never going to get 1.1 out of it. It'll be truncated to 1. Every time.

Use / 10.0 there to force it all to be floating-point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM