【问题标题】:Why is my program looping too many times?为什么我的程序循环次数过多?
【发布时间】:2014-04-01 16:47:18
【问题描述】:

我是 C 的初学者,正在尝试创建一个程序,但我的 main 函数有问题。

问题:

  1. 在询问他们想要输入多少个整数后,例如:4 个数字,循环进行 5 次,基本上输入 5 个数字。它也只在第二个数字之后打印“Next:”。

  2. 在我用于错误检查的while循环中,在用户输入有效方法后,例如:输入1,它将打印出这是一个“无效的选择”并仅重新询问再来一次。

代码:

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

int main() {
  StackType stk;
  StackType *stkPtr = &stk;

  //Will be used to check whether to use recursive or iterative
  int method = 0;
  int sum;
  int *sumPnt = &sum;

  //Will be used to create array for amount of ints:
  int numOfIntegers;

  //Array of ints:
  int *userInts;
  printf("How many integers would you like to enter? "); 
  scanf("%d", &numOfIntegers);
  userInts = (int*)calloc(numOfIntegers, sizeof(int)); //Create the array

  printf("Please enter %d numbers: \n", numOfIntegers);
  int i;
  for (i = 0; i < numOfIntegers; i++) {
    scanf("%d\n", &userInts[i]);
    printf("Next:");
  }

  while(1) {
    printf("Would you like to used iterative or recursive to sum?\n");
    printf("Enter 1 for iterative or 2 for recursive: ");
    scanf("%d\n", &method); 
    if (method == 1) {
      //found in loop.c
      sumIterative(stkPtr, numOfIntegers, userInts, sumPnt);
      break;
    } else if (method == 2) {
      //Found in loop.c
      sumRecursive(stkPtr, numOfIntegers, userInts, sumPnt);
      break;
    } else {
      printf("Invalid choice. Repeating... \n");
        continue;
    }
  } 

  printf("Your sum is: %d", *sumPnt);
    return 0;
}

【问题讨论】:

    标签: c loops while-loop


    【解决方案1】:

    scanf("%d\n", &amp;userInts[i]); 替换为scanf("%d", &amp;userInts[i]);

    有关在 scanf 的格式说明符中输入非空白字符的信息,请参阅 this

    上面写着:

    任何字符 这既不是空白字符(空白、换行符或制表符),也不是 格式说明符的一部分(以 % 字符开头)导致 函数从流中读取下一个字符,将其与 此非空白字符,如果匹配,则将其丢弃并 该函数继续使用格式的下一个字符。如果 字符不匹配,函数失败,返回离开 流的后续字符未读。

    【讨论】:

      【解决方案2】:

      在格式字符串不以\n 结尾的所有printf 语句之后添加fflush(stdout)。否则只有在下一个\n输出后才会显示输出。

      【讨论】:

        【解决方案3】:

        问题一:

        只需替换:

        scanf("%d\n", &userInts[i]);
        

        scanf("%d", &amp;userInts[i]);

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-09-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-10
          • 1970-01-01
          相关资源
          最近更新 更多