c - C 为什么 for 循环没有像它应该的那样迭代多次?
问题描述
我试图要求 K 数量的单词将它们添加到矩阵中。我有两个问题:
我试图设定 strlen(string) 必须小于 n(matrix size) 的大小。但是当它进入 do while 循环时,它永远不会退出。
如何使 for 循环重复直到输入 k 个单词?
几天前我已经尝试过了,而且做的很好。直到我改变了一些东西,它变得一团糟。
/* Enter the matrix dimension */
int n;
do{
printf("\nEnter the matrix size");
scanf("%d", &n);
}while(2>n);
/* Ask for the amount of words the user will enter */
int k;
do{
printf("\nInsert how many words you will enter:");
scanf("%d", &k);
}while(k<0);
/* k Words loop */
int amountOfWords=0;
char string[20];
int i;
for(i=0; i<k; i++, amountOfWords++)
{
do {
printf("\nEnter the %d word:\n", amountOfWords+1);
scanf("%s", &string);
}while(strlen(string) > n);
}
解决方案
你想要做的是接受一个数组而不是矩阵(这不是正确的方法你为什么要在循环中询问矩阵的大小?)。
如果您尝试使用矩阵,您可以按照以下方式进行操作:
/*Ask for the size of matrix */
matrix[rowSize][coulmnSize]
printf("\n Enter the no of row in the matrix");
scanf("%d", &rowSize);
printf("\n Enter the no of columns matrix");
scanf("%d", &coulmnSize);
/* Accept the matrix */
for(int i =0;i<rowSize; i++)
{
for(int j =0;j<coulmnSize; j++)
{
scanf("%d",& matrix[rowSize][coulmnSize]);
}
}
/* Do your stuff */
for(int i =0;i<rowSize; i++)
{
for(int j =0;j<coulmnSize; j++)
{
//Your code here
}
}
你的代码
/* 输入矩阵维度 */
int n;
do{
printf("\nEnter the matrix size");
scanf("%d", &n);
}while(2>n);
Do while 总是执行一次:
所以这就是你编译代码时发生的事情。
1. 它要求您输入矩阵大小 2. 假设您输入1 3. 由于条件为真,它循环并转到步骤 1。 4. 在下一轮您输入 5 它退出循环。
基本上循环在这里没有意义。
这是一维数组的方法。
printf("\nEnter the matrix size");
scanf("%d", &n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
推荐阅读
- roblox - 如何在 Roblox Studio 中检查 vector3 值是否在 region3 值中?
- javascript - 如何求两个数的公质因数?javascript
- r - 使用 ggplot2 将图例放入多线图
- python - Python - 使用 pandas 从 excel 中匹配和提取数据
- swift - Swift 模态视图控制器。有没有一种简单的方法可以找到 ViewController 的结果
- typescript - 如何正确实现动态哈希图的接口?
- html - 如何防止 css'::after 选择器在表中创建新列
- typescript - 将 Map 与函数重载一起使用时,没有重载匹配此调用
- flutter - 没有 pull_to_refresh 的“未定义命名参数keyboardDismissBehavior”
- c++ - 保证 f(ULLONG_MAX) * f(ULLONG_MAX) 不大于 ULLONG_MAX 的公式