gpt4 book ai didi

c - 为什么我的程序循环次数太多?

转载 作者:太空狗 更新时间:2023-10-29 16:12:36 26 4
gpt4 key购买 nike

我是 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;
}

最佳答案

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

参见 this关于在 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.

关于c - 为什么我的程序循环次数太多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22099300/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com