gpt4 book ai didi

c++ - 将简单的 for 循环转换为 while 循环?

转载 作者:太空宇宙 更新时间:2023-11-04 11:25:41 25 4
gpt4 key购买 nike

如何使用 while 循环而不是 for 循环来编写相同的代码?

int n;
cin >> n;

for (int i = 1; i <= n; i++) {
for (int j = n; j >= i; j--) {
cout << j;
}
cout << endl;
}

这是我的尝试,但没有达到同样的效果。我不确定为什么。

int n;
cin >> n;
int i = 1;
int j = n;

while (i <= n) {
while (j >= i) {
cout << j;
j--;
}
i++;
cout << endl;
}

最佳答案

您必须在 while(j >= i) 循环之前重置 j

while (i <= n) {
j = n; //<<<<<<<< Reset j to the starting value
while (j >= i) {
cout << j;
j--;
}
i++;
cout << endl;
}

关于c++ - 将简单的 for 循环转换为 while 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26773986/

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