我是 C 初学者,正在尝试创建一个程序,但我的主要功能有问题。
Problem:
在询问他们想要输入多少个整数(例如:4 个数字)后,循环进行 5 次,基本上输入 5 个数字。它还只在第二个数字之后打印“Next:”。
In my while
循环,我将其用于错误检查,在用户输入有效方法后,例如:输入1,它将打印出这是一个“无效选择”,并仅再次重新询问一次。
Code:
#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 = ∑
//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;
}
Replace scanf("%d\n", &userInts[i]);
with scanf("%d", &userInts[i]);
See this http://www.cplusplus.com/reference/cstdio/scanf/关于在 scanf 的格式说明符中输入非空白字符。
It says:
任意角色
不是空白字符(空白、换行符或制表符)或
格式说明符的一部分(以 % 字符开头)会导致
函数从流中读取下一个字符,并将其与
这个非空白字符,如果它匹配,它将被丢弃并且
该函数继续处理格式的下一个字符。如果
字符不匹配,函数失败,返回并离开
流的后续字符未读。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)