如何使用嵌套的环C 扣除100至零

How to deduct 100 to zero using nested for loop c++

本文关键字:扣除 至零 何使用 嵌套      更新时间:2023-10-16

基本上我的程序是由两个人扣除100,直到达到零为止。我正在使用嵌套进行循环。每个人都需要进入整数,每个人都需要1个循环。该整数将用100。

扣除

,但主要的问题是我不能在不失去当前值100的情况下重复第一个循环。我是初学者。

for( int x = 1; x<=100;)
{
  cout <<"nn"<< nP1 <<" how many of the remaining " << chips<<" chip(s) would you like?"<<endl;
  cin >> P1c;
  result = chips-P1c;
  cout <<result;
    for( int y = 1; y <=100;)
    {
    cout <<"nn"<< nP2 <<" how many of the remaining " << result<<" chip(s) would you like?"<<endl;
    cin >> P2c;
    result = result-P2c;
    cout <<result;
    break;
    }

屏幕截图

for-loops不适合此 - "重复直到您描述问题为零",与"重复一百次"非常不同,就像您一样试图解决它。

如果您在现实生活中玩这个,您可能会做这样的事情:

while there are any chips left
   let person 1 pick some chips
   if there are still any chips left
       let person 2 pick some chips

将左右的代码转换为练习。

我想您要模拟的是一群用一袋薯条吃饭的人。您当前代码的问题是2倍。Y和X永远不会减少,但您甚至不应该将X和Y用作您的计数器。您应该将袋子中的芯片数作为柜台,并在每个人吃饭后将其减少。

虽然循环更适合此问题。但是,如果您必须用于循环...

int num_people = 2;
int people[num_people];
int tmp;
// Begin eating
for (int chips = 100; chips > 0;)
{
    // Rotate through group of people
    for (int i = 0; i < num_people; i++)
    {
        printf("Person %d take chips >n", i);
        cin >> tmp;
        // No person can take more than the remaining chips
        tmp = max(tmp, chips);
        // Increment chip eating total for each person
        people[i] += tmp;
        chips -= tmp;
        // Break the rotation if there are no more chips to eat
        if (chips <= 0)
        {
            break;
        }
    }
}
// Lets see who ate how many for fun
for (int i = 0; i < num_people; i++)
{
    printf("Person %d had %d chipsn", i, people[i]);
}
return 0;