C不会将负数识别为输入

时间:2016-11-24 22:42:46

标签: c if-statement operators

此程序旨在将三个整数作为输入并返回最小值。这是我的第一次尝试:

int first, second, third;
printf("Please enter three numbers:\n");
scanf("%d %d %d", &first, &second, &third);
int min;
if (first<second && first<third) {
    min = first;
} else if (second<first && second<third) {
    min = second;
} else {
    min = third;
printf("The minimum value is: %d\n", min);
}

它适用于除负数之外的所有事物。如果输入为负数,则不会返回任何内容。然后我将代码更改为:

if (first<second ) {
    if (first<third)
        min = first;
    else
        min = third;
} else if (second<first) {
    if (second<third)
        min = second;
    else
        min = third;
    min = second;
}
printf("The minimum value is: %d\n", min);

这个版本运行得很好,但我不明白为什么第一个版本不能用于否定。有什么区别?

1 个答案:

答案 0 :(得分:1)

你在else {printf}中有printf,它应该在外面:

    int first, second, third;
printf("Please enter three numbers:\n");
scanf("%d %d %d", &first, &second, &third);
int min;
if (first<second && first<third) {
    min = first;
} else if (second<first && second<third) {
    min = second;
} else {
    min = third;
}
printf("The minimum value is: %d\n", min);
}