如何打印一组输入整数中最小的数字?
我想编写一个程序,提示人们输入一组用空格分隔的整数。用户应该能够输入任意数量的整数。它将找到集合中两个最小的整数并将其打印出来。打印最小的数字,然后打印第二小的数字。我的问题是如何使 min1 的值成为他们输入的第一个整数,而不是静态整数?当我进行测试运行时,它打印的所有内容都是空格,这是为什么?这是我到目前为止所得到的:
更新: 我现在正在尝试这种方法,但在输入 76 5 74 2 等输入后它就会冻结。
#include <stdio.h>
int min1, min2;
int input;
int main(){
printf("Please enter some integer: ");
scanf("%d", &min1);
while(scanf("%d", &input) != 0){
min1=input;
}
printf("%d", min1);
return 0;
}
I want to write a program where it prompts people to enter a set of integers separated by a space. The user should be able to enter any amount of integer. It will find the two smallest integer in the set and print it out. Printing the smallest number and then printing the second smallest. My question is how do I get the value of min1 to be the first integer they enter, other than a static one? When I did a test run all it printed was a space, why is that? Here is what I have so far:
Update:
I'm now trying this approach, but it just freeze after I enter an input such as 76 5 74 2.
#include <stdio.h>
int min1, min2;
int input;
int main(){
printf("Please enter some integer: ");
scanf("%d", &min1);
while(scanf("%d", &input) != 0){
min1=input;
}
printf("%d", min1);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您应该在第一个 printf 的末尾添加
\n
,这样它就不会被缓冲。另外,请注意您使用的是数字,而不是整数。
对于您的问题 - 只需编写
min1=getchar();
。编辑:一些代码可能会执行您想要的操作:
You should add
\n
in the end of the first printf, so it will not buffered.Also, be care that you work with digits - not integers.
and for your question - just write
min1=getchar();
.EDIT: some code that may do what that you want:
也许您需要
scanf("%d", &number);
来读取整数。对于您的问题,只需调用
scanf
读取第一个数字,或设置一个标志来指示它是否是第一个输入。Maybe you need
scanf("%d", &number);
to read integers.For your question, just call
scanf
to read the first number, or set up a flag to indicate if it's the first input.为什么你打印了一个空格?因为 %c 打印字符而不是数字,所以尝试 %d。
但即使在那之后你也不会得到你正在寻找的答案。 getchar() 从用户输入中获取一个字符(如图...),并且您将该字符存储到一个数值中,对于单位数字,它会神奇地工作,因为即使是字符 '9 ' > '8'> '7'> ...>> '0',但你会得到最后打印的最小数字的 ascii 值。
Why did you got a space printed? Because %c prints characters not numbers, try %d.
But even after that you won't get the answer you are looking for.
getchar()
gets a character (go figure...) from the user input, and you are storing that character into a numeric value, for single digit numbers it would magically work since even as characters '9' > '8' > '7' > ... > '0', but you'll get the ascii value of the smallest number printed at the end.您需要两件事:
在 sudocode 中,可能类似于:
You need two things:
In sudocode, maybe something like: