gpt4 book ai didi

c - 如何在循环中为数组设置特定值? - C

转载 作者:行者123 更新时间:2023-11-30 20:53:22 26 4
gpt4 key购买 nike

我正在学习初级编程类(class),我们的任务是编写一个 10 人开始的游戏程序。你从第一个人开始,数到 3 个人,然后丢弃那个人。你继续这样做,直到只剩下一个人。

#include <stdio.h>
#include <stdlib.h>

int main()
{
int n[10] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, i = 0;
int * ptrN = &n[i];

for( i = 0; n[i]; n[i+3]){

if (n[i+3] = 1){
*ptrN = 0;
}
else if (n[i] = 0)
continue;
else
printf("Wrong");
}
printf("The value of n0 %d\tn1 %d\tn2 %d\tn3 %d\tn4 %d\tn5 %d\tn6 %d\tn7 %d\tn8 %d\tn9 %d", n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7], n[8], n[9]);
return 0;
}

我现在离我的答案还很远,但我已经遇到了问题。当我运行上面的代码时,它只会更改 n[0] 的值,然后退出程序。将不胜感激任何指导。谢谢

最佳答案

正如评论中提到的:

  1. 使用==进行比较,=用于赋值。
  2. 您不需要使用指针。您可以使用n[i]
  3. 您需要增加i
  4. 您需要跳过 0

正如您所提到的,当只剩下一个 1 时,您也需要停止。

解决这个问题的方法不止一种,但你可以通过一个计数器来计算有多少个 1,并使用一个 while 循环来实现这一点。当计数器减至 1 时结束:

#include <stdio.h>
#include <stdlib.h>

int main()
{
int n[10] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, count = 10;

/* `i` needs to start at -1 so that we start counting:
* "0, 1, 2. n[2] is out!"
* instead of counting:
* "1, 2, 3. n[3] is out!"
*/
int i = -1;

while (count > 1) {

/* We need to count three of those persons that are not out.
* That means we have to search for the next person that is not
* out (by skipping over `0`) and repeat that three times.
*
* If we just increase `i` by 3 ( `(i + 3) % 10` ) then we are
* not checking how many of those persons between `n[i]` and
* `n[(i + 3) % 10]` needed to be skipped over.
*
* So repeat three times:
*/
for (int j = 0; j < 3; j++) {

/* This will search for the next person that is not out by
* increasing `i` by one until `n[i]` is not `0`:
*/
do {
i = (i + 1) % 10;
} while (n[i] == 0); // Check next person if this one is out.

} // I forgot to close this bracket in my first version of the answer

n[i] = 0;
count--;
}

printf("The value of n0 %d\tn1 %d\tn2 %d\tn3 %d\tn4 %d\tn5 %d\tn6 %d\tn7 %d\tn8 %d\tn9 %d", n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7], n[8], n[9]);
return 0;
}

关于c - 如何在循环中为数组设置特定值? - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49158813/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com