I was wondering if I could get some help with a problem that I am having.
Basically, I am trying to end my program by using a while loop when the people count gets to 150.
My math seems to be right, but for some reason, the program ends when it gets to people count 276.
Can anyone help with this issue? Thanks!
Code Input:
int main () {
// declare variables
int weeks=0, people=5;
while (people < 150) {
weeks++;
people=(people-weeks)*2;
printf("On week %d Professor Rabnud's Social Media Group has %d people\n", weeks, people);
}
// end program
return 0;
}
Code Output:
On week 1 Professor Rabnud's Social Media Group has 8 people
On week 2 Professor Rabnud's Social Media Group has 12 people
On week 3 Professor Rabnud's Social Media Group has 18 people
On week 4 Professor Rabnud's Social Media Group has 28 people
On week 5 Professor Rabnud's Social Media Group has 46 people
On week 6 Professor Rabnud's Social Media Group has 80 people
On week 7 Professor Rabnud's Social Media Group has 146 people
On week 8 Professor Rabnud's Social Media Group has 276 people
int main () {
// declare variables
int weeks=0, people=5;
while (people < 150) {
weeks++;
people=(people-weeks)*2;
printf("On week %d Professor Rabnud's Social Media Group has %d people\n", weeks, people);
}
// end program
return 0;
}
As you can see, when week == 7
then people == 146
Because 146 < 150
is true
, the loop is executed again. First, it increment week
so now week == 8
, then, it caculated people
. (146 - 8) * 2 == 276
, so people
is now 276
Then it executed the printf()
statement. Only now, 276 < 150
is false
, then the loop terminated.
Because we know when week == 1
then people == 8
we can do this:
int main () {
// declare variables
int weeks=1, people=8;
while (people < 150) {
printf("On week %d Professor Rabnud's Social Media Group has %d people\n", weeks, people);
weeks++;
people=(people-weeks)*2;
}
// end program
return 0;
}
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.