Hello, why cant I prevent 'l' from becoming less than 0 in while loop ? It still does one final loop while 'l' is still more than 0, which then turns it to 'l<0'. Thank you.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
usingnamespace std;
int main()
{
int v=53,sk=0,h,l=7500;
while(l>=0&&sk<=7)
{
sk++;
h=sk*sk;
l-=h*v;
cout << "L=" << l << endl;
}
return 0;
}
Thank you for your answer. I dont really know yet what
l > (h * v) ? l -= h * v : break;
does, but I tried replacing my old line with this one and im receiving syntax 'break' error. I feel like its similiar to :
1 2 3 4 5
if(l > h * v)
{
l -= h * v
break;
}
Am I right ?
Also, this code's "story" is :
Elephant with weight of 7500kg(l) died. sk2 animals come each day to eat it. Every animal weights 53kg(v). If they cant finish eating it in 7 days, loop should stop and show how much elephant weights now. If they have finished eating it in less than 7 days, it should show how many days they were eating it.
I havent included days as output yet, because loop isnt working as expected anyway.
The reason the break doesn't work in the ternary operator is that it doesn't set a value. The standard says that the expression after the : has to be an assignment expression.
I'd change the code to loop through the days and break out of the loop if the elephant is consumed:
1 2 3 4 5 6 7 8 9 10 11
int elephantWeight = 7500;
int day;
for (day=1 day < 8; ++day) {
int numAnimals = day*day;
elephantWeight -= numAnimals * 53;
if (elephantWeight <= 0) {
cout << "after " << day << " days the corpse is consumed.\n";
break;
}
cout << "after " << day << " days the corpse weighs " << elephantWeight << ".\n";
}