【问题标题】:C Why does the for loop only not iterate as many times as its supposed to?C 为什么 for 循环没有像它应该的那样迭代多次?
【发布时间】:2019-08-04 20:46:58
【问题描述】:

我正在尝试询问 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);
    }

【问题讨论】:

  • 我看不出你的代码有什么问题。第一个循环读取n大于或等于2,第二个循环读取k大于或等于0for循环读取k长度小于或等于@987654328的单词@.

标签: c arrays string matrix


【解决方案1】:

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

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

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

【讨论】:

  • 前两个do 用于验证nk 的输入值。
  • 当我提到 do while 循环是要求 strlen(string) 循环的那个。
猜你喜欢
  • 1970-01-01
  • 2011-07-27
  • 2017-10-13
  • 1970-01-01
  • 2020-01-09
  • 1970-01-01
  • 2023-01-27
  • 1970-01-01
  • 2023-02-20
相关资源
最近更新 更多