c - 编程中的嵌套循环
问题描述
我将如何使用下面的代码显示内部 while 循环内的迭代次数。我想从外部循环的迭代次数中迭代内部循环。
printf("value: ");
scanf("%d", &x[0]);
/*printf("%d", x[0]);*/
loop: while(a < x[0])
{
while(b < x[0]) {
b++;
}
printf("%d %d\n", a, b);
a++;
goto loop;
}
}
解决方案
为什么你使用while
循环?当您知道迭代次数时,请始终使用for
循环。您知道迭代次数,因为您将其设置为输入。
所以你可以重写你的代码(基于你提供的稀有信息并且没有输入检查):
#include <stdio.h>
int main(void)
{
int Input;
printf("Enter a value: ");
scanf("%d", &Input);
for(int i = 0; i < Input; i++)
{
for(int j = 0; j <= Input; j++)
{
printf("%d %d\n", i, j);
}
}
return 0;
}
或带有while
循环(不良风格)
#include <stdio.h>
int main(void)
{
int i = 0;
int j = 0;
int Input;
printf("Enter a value: ");
scanf("%d", &Input);
while(i < Input)
{
j = 0;
while(j <= Input)
{
printf("%d %d\n", i, j);
j++;
}
i++;
}
return 0;
}
两种方式都会为您提供以下输出:
Enter a value: 2
0 0
0 1
0 2
1 0
1 1
1 2
推荐阅读
- nginx - 我需要关于设置 Nginx 的建议
- reactjs - react JS属性与属性不同吗?
- node.js - 如何轻松创建参赛表格
- sharepoint - Sharepoint 设计器工作流程:多项选择字段的条件
- git - 奇怪的 git 问题。Git pull 导致文件更改
- three.js - 如何使用 Threejs 编辑器中的 KHR_materials_pbrSpecularGlossiness 导出 GLTF 模型
- reactjs - 如何使用 React Router 在 React 中渲染这个对象?
- android - androidx getFragmentManager() 已被弃用
- css - css中多级导航栏的平滑悬停效果
- php-7.2 - OroCRM - Symfony 类在将 PHP 版本从 7.1 升级到 7.2 后找不到 PHP 可执行二进制文件