为什么我的程序循环太多? [英] Why is my program looping too many times?

查看:72
本文介绍了为什么我的程序循环太多?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C语言的初学者,试图创建一个程序,但我的主要功能有问题.

I'm a beginner in C and trying to create a program and having a problem with my main function.

问题:

  1. 在询问了他们要输入多少个整数后,例如:4个数字,循环进行了5次,实际上吸收了5个数字.它还仅在第二个数字之后打印"Next:".

  1. After asking how many integers they'd like to enter, for example: 4 numbers, the loop goes on 5 times essentially taking in 5 numbers. It also only prints "Next: " after the 2nd number.

在我的while循环中(我用于进行错误检查),在用户放置有效方法之后,例如:输入1,它将打印出它是无效选择",并且仅再次询问再次.

In my while loop, which I put for error checking, after the user puts a valid method, example: enters 1, it will print out that it's an "invalid choice" and re-asks again only once more.

代码:

#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;
}

推荐答案

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

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

See this about entering a nonwhitespace character in format specifier in scanf.

它说:

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

Any character that is not either a whitespace character (blank, newline or tab) or part of a format specifier (which begin with a % character) causes the function to read the next character from the stream, compare it to this non-whitespace character and if it matches, it is discarded and the function continues with the next character of format. If the character does not match, the function fails, returning and leaving subsequent characters of the stream unread.

这篇关于为什么我的程序循环太多?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆