【问题标题】:C: why does my program not continue after while loop? (scanf)C:为什么我的程序在while循环后不继续? (扫描)
【发布时间】:2021-04-09 11:12:41
【问题描述】:

我目前正在学习 C 并想编写一个程序,该程序采用数字 ganzeZahl 来确定数组长度。

然后您必须输入存储在大小为n 的数组中的数字,然后它应该进行选择排序(我在这里剪掉了,因为我的程序甚至没有到达那部分)。

每当我尝试运行 while 循环时,我都无法通过它。它编译得很好。 它永远不会到达printf("!!!--------!!!"); //由于某种原因没有到达这部分?测试5。

#include<stdio.h>

int main() {

  int ganzeZahl;
  scanf("%d", &ganzeZahl);
  //printf("ganze Zahl ist: %d\n", ganzeZahl); //test

  int array[ganzeZahl];
  int i = 0;

  for(int z = 0; z < ganzeZahl; z++) {
    printf("%d\n", array[z]);
  }

  while(i<ganzeZahl) {
    //printf("!!!hier!!!\n"); //test2

    scanf("%d", &array[i]);
    //printf("zahl gescannt!\n"); //test 3
    i++;
    //printf("i erhöht!\n"); //test 4
  }

  printf("!!!--------!!!"); //this part isn't reached for some reason? test5
  //selection sort here
//[...]

  return 0;
}

【问题讨论】:

  • 无法重现 - 当我使用 ganzeZahl 输入 3 进行测试时,您的程序运行良好,然后输入 11 22 33。您输入了什么?以及如何?
  • 只是一个想法——也许在你的“丢失”printf 调用中添加一个换行符:printf("!!!--------!!!\n");——只是为了确保输出缓冲区被刷新。
  • 将循环打印结果从before数据输入移动到after
  • 在用scanf 填充之前,您不应该打印array 的内容(请参阅here),但代码似乎可以正常工作(请参阅快速ideone

标签: c while-loop scanf


【解决方案1】:

您的程序确实执行正确,并最终到达最后一个printf 调用。

当它进入whileloop 时,它继续调用scanf,是什么导致它停止并等待,直到你每次迭代输入一个值。如果您提供ganzeZahl 输入(输入数字并按“输入”),它将完成循环并继续。我想如果你在循环中的scanf 之前添加一个printf,它应该更直观。

【讨论】:

  • 哦,天哪,那肯定是后面的部分打断了。非常感谢!我想我应该先测试一下。无论如何,感谢您抽出宝贵的时间
【解决方案2】:
for(int z = 0; z < ganzeZahl; z++){
printf("%d\n", array[z]);

数组没有初始化,所以你还不能打印数组。

其实你搞乱了代码的顺序。while 循环应该先出现,然后是 for 循环。我在下面更正了您的代码。编码愉快!

#include<stdio.h>

int main() {

  int ganzeZahl;
  scanf("%d", &ganzeZahl);
  //printf("ganze Zahl ist: %d\n", ganzeZahl); //test

  int array[ganzeZahl];
  int i = 0;

 while(i<ganzeZahl) {
    //printf("!!!hier!!!\n"); //test2

    scanf("%d", &array[i]);
    //printf("zahl gescannt!\n"); //test 3
    i++;
    //printf("i erhöht!\n"); //test 4
  }
  
  for(int z = 0; z < ganzeZahl; z++) {
    printf("%d\n", array[z]);
  }


  printf("!!!--------!!!"); //this part isn't reached for some reason? test5
  //selection sort here
//[...]

  return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-25
    • 2015-01-15
    • 2014-03-11
    • 1970-01-01
    • 2013-02-13
    • 2020-05-11
    • 1970-01-01
    相关资源
    最近更新 更多