|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- struct peo{
- int num;
- int sign;
- };
- int peo_del(struct peo *p){
- int count = 0,sum=13;
- struct peo *p1=p;
- while(sum-1){
- if((*p).sign==0){
- continue;
- }
- count++;
- if(count==3){
- (*p).sign=0;
- sum--;
- count=0;
- }
- p++;
- }
- while(1){
- if((*p1).sign==1){
- return (*p1).num;
- }
- p1++;
- }
-
- }
- int main(){
- struct peo cir[13]={{1,1},{2,1},{3,1},{4,1},{5,1},{6,1},{7,1},{8,1},{9,1},{10,1},{11,1},{12,1},{13,1}};
- printf("剩下的是:%d",peo_del(cir));
- }
复制代码
这段代码有什么问题吗,是不是陷入了死循环,vscode执行没有输出
这段代码确实存在问题,导致了死循环并且没有输出结果。问题出现在`peo_del`函数的最后一个`while`循环中。
在这个循环中,我们使用了指针`p1`来遍历数组找到标记为`1`的元素,并返回其`num`值。然而,当已经遍历到数组末尾时,`p1`指针并没有得到更新,仍然指向数组的最后一个元素。由于该元素的`sign`仍然为`1`,所以循环会一直继续下去,导致了死循环。
为了解决这个问题,我们可以通过在循环中添加一个判断条件来退出循环,例如当`p1`指向数组首地址时,即`p1 == cir`时,即可退出循环。
以下是修改后的代码:
- #include <stdio.h>
- #include <stdlib.h>
- struct peo{
- int num;
- int sign;
- };
- int peo_del(struct peo *p){
- int count = 0, sum = 13;
- struct peo *p1 = p;
- while (sum-1){
- if ((*p).sign == 0){
- continue;
- }
- count++;
- if (count == 3){
- (*p).sign = 0;
- sum--;
- count = 0;
- }
- p++;
- }
- while (1){
- if ((*p1).sign == 1){
- return (*p1).num;
- }
- p1++;
- if (p1 == p){
- break;
- }
- }
- return -1; // 没有找到标记为1的元素
- }
- int main(){
- struct peo cir[] = {
- {1, 1}, {2, 1}, {3, 1}, {4, 1}, {5, 1}, {6, 1},
- {7, 1}, {8, 1}, {9, 1}, {10, 1}, {11, 1},
- {12, 1}, {13, 1}
- };
- printf("剩下的是:%d\n", peo_del(cir));
- return 0;
- }
复制代码
修改后的代码中,我们添加了一个判断条件`if (p1 == p)`,如果`p1`指向了数组首地址,即已经遍历完整个数组,就会退出循环。同时,我们在`main`函数中添加了`return 0;`语句,以确保程序正常结束。
请注意,根据您的逻辑,最后返回的结果应该是一个标记为`1`的元素的`num`值。我在代码中添加了一个返回值为`-1`的情况,表示没有找到标记为`1`的元素。可以根据实际需要自行进行修改。
以上回复来自 -- ChatGPT(FishC官方接口),如未能正确解答您的问题,请继续追问。
|
|