这就是我想要做的: 我的老师给了我一个作业,以接收来自用户的输入,例如“ 1,2,3,4,-3,17,-9,0,5,-8,10”,并且在用户按下Enter键之后,忽略“,”号,并打印正数和负数的最大值和最小值(每个)。 现在他说我们应该使用getchar()来做到这一点,但我不知道如何...我知道此函数用于从用户读取单个字符(并使用putchar()打印),而不是用于忽略字符,所以我想了解如何在while循环中使用它来进行这种操作。
因此,总结一下我的问题是关于有选择地读取输入(其他事情我将自己处理,尽管如果有人看到了代码中的某些内容并可以给出提示,我会很高兴,但我希望了解getchar()函数来做与我正在阅读的设计相反的工作),我已经编写和删除了数千次代码,无法使其正常工作……这是现在的样子(并且不起作用) ):
#include <stdio.h>
#include <stdlib.h>
int main(){
char enter = "\n";
int list_of_nums[100];
char ch1[100];
int neg_num[100];
int pos_num[100];
printf("please enter numbers separated by ',': \n");
while (getchar()!= enter) {
scanf("%d" ,&list_of_nums;
if (list_of_nums >= 0){
getchar();
pos_num.append(list_of_nums);
}
else{
neg_num.append(list_of_nums);
}
}
int max_pos = max.pos_num[];
int min_pos = min.pos_num[];
int max_neg = max.neg_num[];
int min_pos = min.neg_num[];
printf("the maximum number of all the positives is: %d \n" ,max_pos);
printf("the minimum number of all the positives is: %d \n" ,min_pos);
printf("the maximum number of all the negatives is: %d \n" ,max_neg);
printf("the minimum number of all the negatives is: %d \n" ,min_neg);
return 0;
}
答案 0 :(得分:0)
根据第一个输入,选择下一个输入。这是负数的代码。只需添加带有两位数数字的大小写并对其进行优化:
#include <stdio.h>
#include <stdlib.h>
#define MAX_NUMBERS 100
int main(void){
int list_of_nums[MAX_NUMBERS];
int pos_nums[MAX_NUMBERS];
int neg_nums[MAX_NUMBERS];
int size = 0, size_pos = 0, size_neg = 0, i, max_pos, min_pos, max_neg, min_neg, neg_flag = 0;
char input;
printf("Enter numbers separated by ',':\n");
do {
input = getchar();
if(input == '-') {
neg_flag = 1; //for negative numbers
input = getchar();
}
if(input >= '0' && input <= '9') {
if(neg_flag) {
list_of_nums[size] = -(input - 48); //FROM ASCII CHARACTER CODE
} else {
list_of_nums[size] = input - 48;
}
neg_flag = 0;
size++;
} else {
neg_flag = 0;
}
} while(input != '\n');
for(i = 0; i < size; i++) {
printf("%d ", list_of_nums[i]);
if(list_of_nums[i] >= 0) {
pos_nums[size_pos] = list_of_nums[i];
size_pos++;
}
else {
neg_nums[size_neg] = list_of_nums[i];
size_neg++;
};
}
printf("\n");
max_pos = pos_nums[0];
min_pos = pos_nums[0];
for(i = 1; i < size_pos; i++) {
if(max_pos < pos_nums[i]) max_pos = pos_nums[i];
if(min_pos > pos_nums[i]) min_pos = pos_nums[i];
}
max_neg = neg_nums[0];
min_neg = neg_nums[0];
for(i = 1; i < size_neg; i++) {
if(max_neg < neg_nums[i]) max_neg = neg_nums[i];
if(min_neg > neg_nums[i]) min_neg = neg_nums[i];
}
printf("The maximum number of all the positives is: %d\n", max_pos);
printf("The minimum number of all the positives is: %d\n", min_pos);
printf("The maximum number of all the negatives is: %d\n", max_neg);
printf("The minimum number of all the negatives is: %d\n", min_neg);
return 0;
}
P.S。为了将来,不要发布“需要功课帮助” 问题,而应尽可能解决问题。这样,您就可以提出更多的研究问题。