C语言 for循环中的做作或问题[已关闭]

rjzwgtxy  于 2022-12-26  发布在  其他
关注(0)|答案(2)|浏览(292)

**已关闭。**此问题为not reproducible or was caused by typos。当前不接受答案。

这个问题是由打字错误或无法再重现的问题引起的。虽然类似的问题在这里可能是on-topic,但这个问题的解决方式不太可能帮助未来的读者。
昨天关门了。
Improve this question
我创建了一个包含两个元素的数组,并尝试比较静态数组,但它们的增量不像预期的那样工作,
预期输出为1 1,但每次输出为0 1
下面是C代码:

#include <stdio.h>
#include <stdlib.h>

int main() {

  int a[] = {1, 2, 3};
  int b[] = {3, 2, 1};

  int *res = malloc(2 * sizeof(int));

  int sumA = 0, sumB = 0;
  for (int k = 0; k < 2; k++) {
    if (a[k] > b[k]) {
      printf("yes a\n");
      sumA += 1;
    } else if (a[k] < b[k]) {
      printf("yes b\n");
      sumB += 1;
    }
  }

  res[0] = sumA;
  res[1] = sumB;

  printf("%d, %d", res[0], res[1]);

  return 0;
}

我试着调试代码,但没有解决方案,我认为for循环是问题所在,我只需要提示或永久解决方案...
找你们帮忙。

bvjxkvbb

bvjxkvbb1#

#include <stdio.h>
#include <stdlib.h>

int main() {
    int a[] = {1, 2, 3}; // 1 is **indexed 0**; 2 is **indexed 1** and 3 is **indexed 2**
    int b[] = {3, 2, 1}; // 3 is **indexed 0**; 2 is **indexed 1** and 1 is **indexed 2**

int *res = malloc(2 * sizeof(int)); //memory allocation

int sumA = 0, sumB = 0; //sumA and sumB are assigned 0

//now loop is k = 0
for (int k = 0; k < 2; k++) {
//a[0] > b[0] //1 > 3 // FALSE so "NO" or 0 for if part but true for else if so it executes it
//It increments as condition is k < 2 so now k = 1;
//a[1] > b[1] //2 > 2 //Both the statements fail as you didnot specify the condition for equals so it just goes out.
//It increments k = 2 and as 2 < 2 so it fails and for loop ends.
    if (a[k] > b[k]) {
    printf("yes a\n");
    sumA += 1; //never executes
    } else if (a[k] < b[k]) {
    printf("yes b\n");
    sumB += 1; //ones executes for indexing 0 which is 1 < 3
    }
}

res[0] = sumA;
res[1] = sumB;

printf("%d, %d", res[0], res[1]);

return 0;
}

//So when res[0] is 0 its because your if statement never executed.
//so when res[1] is 1 because your else if executed once for indexing [0]
//indexing [1] failed because there is no condition for equals

//so you got the result 0 1 and not 1 1 because if statement never executed so your sumA += 1 never executed so value never changed.
ql3eal8s

ql3eal8s2#

你没有遍历所有3个有效的索引。

for (int k = 0; k < 3; k++)

注意:您可以使用sizeof a / sizeof *a来计算数组中的元素数。

相关问题