鱼C论坛

 找回密码
 立即注册
查看: 2966|回复: 3

一个莫名其妙的死循环,问题在哪??

[复制链接]
发表于 2012-4-18 12:03:11 | 显示全部楼层 |阅读模式
7鱼币
#include <stdio.h>
#include <stdlib.h>
#define N 20

void swap(char *p1,char *p2)
{
    char temp;
    temp = *p1;
    *p1 = *p2;
    *p2 = temp;
}

void reverse_string(char *string)
{
    int mid,all,count = 1;
    char *p1 = string,*p2 = string;
    all = 1;
    while(*p2 != '\0')
    {
        all++;
        p2++;
    }
    all--;
    p2--;
    mid = all/2;
    while(count <= mid)
    {
        swap(p1,p2);
    }

}

int main()
{
    char a[] = "abcdefg";
    printf("%s\n",a);
    reverse_string(a);
    printf("%s\n",a);

    return 0;
}
陷入死循环了  但我看不出问题在哪  大仙们 帮帮忙啊

最佳答案

查看完整内容

#include #include #define N 20 void swap(char *p1,char *p2) { char temp; temp = *p1; *p1 = *p2; *p2 = temp; } void reverse_string(char *string) { int mid,all,count = 1; char *p1 = string,*p2 = string; all = 1; while(*p2 != '\0') { all++; p2++; } all--; p2--; mid = all/2; while(count
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
发表于 2012-4-18 12:03:12 | 显示全部楼层
#include <stdio.h>
#include <stdlib.h>
#define N 20

void swap(char *p1,char *p2)
{
    char temp;
    temp = *p1;
    *p1 = *p2;
    *p2 = temp;
}

void reverse_string(char *string)
{
    int mid,all,count = 1;
    char *p1 = string,*p2 = string;
    all = 1;
    while(*p2 != '\0')
    {
        all++;
                p2++;
    }
    all--;
        p2--;
    mid = all/2;

    while(count <= mid)
    {
        swap(p1,p2);
                p1++;
                p2--;
                count++;      //没有循环终止条件
    }
}

int main()
{
    char a[] = "abcdefg";
    printf("%s\n",a);
    reverse_string(a);
    printf("%s\n",a);
        return 0;
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2012-4-18 12:26:04 | 显示全部楼层
这句 while(count <= mid) 出问题了。。 是不是应该把 while 改为 if 呢?if(count <= mid)
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2012-4-18 12:50:31 | 显示全部楼层
楼上答得很对哦!你这个程序的意思,是想把一个字符串反向输出吧!
while()要有终止循环的语句才行。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-20 17:48

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表