首页 > 解决方案 > C 为什么 for 循环没有像它应该的那样迭代多次?

问题描述

我试图要求 K 数量的单词将它们添加到矩阵中。我有两个问题:

  1. 我试图设定 strlen(string) 必须小于 n(matrix size) 的大小。但是当它进入 do while 循环时,它永远不会退出。

  2. 如何使 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);
    }

标签: carraysstringmatrix

解决方案


你想要做的是接受一个数组而不是矩阵(这不是正确的方法你为什么要在循环中询问矩阵的大小?)。

如果您尝试使用矩阵,您可以按照以下方式进行操作:

/*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]);
}

推荐阅读