user9484
user9484

Reputation: 1

C won't recognize negative numbers as input

This program is meant to take three whole numbers as input and return the minimum. This was my first attempt:

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);
}

It worked for everything except negative numbers. If an input was negative, it would not return anything. Then I changed the code to this:

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);

This version worked perfectly, but I don't understand why the first one wouldn't work for negatives. What's the difference?

Upvotes: 0

Views: 1056

Answers (1)

Gumboy
Gumboy

Reputation: 467

You had the printf in the else{printf} it should be outside:

    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);
}

Upvotes: 1

Related Questions