c++中为什么我用do{}while循环不起来

img


这个是原题
下面是我的代码
一种是for循环(结果正确)
二种是dowhile循环(我用了分布执行 发现do只执行了第一次 就没有循环了)

img

img

为什么这个do while 循环不起来呢

do...while 的while后面有个分号的哦
并且你do while这个程序里面的 i 没有初始化,所以执行不了
修改如下:

#include<stdio.h>
int main()
{
    int n, i=1, j;
    int ch[100];
    scanf_s("%d", &n);
    if (n > 0 && n <= 100)
        ch[0] = n;
    do
    {
        if (n % 2 == 1)
        {
            n = n * 3 + 1;
            ch[i] = n;
            i++;
        }
        else
        {
            n = n / 2;
            ch[i] = n;
            i++;
        }
    }while (n != 1);
    
    for (j = 0; j <= i - 1; j++)
        printf("%d ", ch[j]);
    return 0;
}

img

#include<stdio.h>
int main()
{
int n, i, j;
int ch[100];
scanf_s("%d", &n);
if (n > 0 && n <= 100)
ch[0] = n;
do
{
if (n % 2 == 1)
{
n = n * 3 + 1;
ch[i] = n;
i++;
}
else
{
n = n / 2;
ch[i] = n;
i++;
}
}while(n==1)
for (j = 0; j <= i - 1; j++)
printf("%d ", ch[j]);
return 0;
}
这是do while的代码