Я не знаю, что может быть, я делаю не так. По логике все мне кажется правильным.
Хотя есть некоторые синтаксические ошибки. Конструкция типа
// ...
if ( a > c ) {
// ...
}
else { // <----
// ...
}
else if ( b > c ) {
// ...
}
недопустима в C.
Мне непонятно, как ОП планировал структурировать вложенные if
s для решения задачи, но до этогоПродолжая, я бы предложил написать несколько простых тестов для проверки правильности алгоритма:
#include <stdio.h>
// Prototype of the function which returns the biggest out of the four arguments
int max_of_four(int a, int b, int c, int d);
// Helper function used to verify the correctness of the results
int test_(int a, int b, int c, int d, int expected)
{
int result = max_of_four(a, b, c, d);
if ( result != expected )
{
printf("FAILED - Expected: %d (given %d, %d, %d and %d), instead of %d.\n",
expected, a, b, c, d, result);
return 1;
}
return 0;
}
// Test runner
int main(void)
{
int failed = 0;
// The function should be able to find the biggest regardless of its "position"
failed += test_(1, 2, 3, 4, 4);
failed += test_(4, 3, 2, 1, 4);
failed += test_(2, 1, 4, 3, 4);
failed += test_(3, 4, 1, 2, 4);
// The function should manage negative values
failed += test_(1, -2, -3, -4, 1);
failed += test_(-4, -3, -2, -1, -1);
failed += test_(0, -3, -1, -2, 0);
// The function should manage duplicate values
failed += test_(1, -2, 1, 2, 2);
failed += test_(-4, -3, -3, -5, -3);
failed += test_(1, 1, 1, 1, 1);
if ( failed == 0 )
puts("So far so good.");
return 0;
}
// A simple implentation.
int max_of_four(int a, int b, int c, int d)
{
int big = a;
if ( b > a )
big = b;
if ( c > big )
big = c;
if ( d > big )
big = d;
return big;
}
Вы можете протестировать его здесь и попытаться переписать функцию, используя вложенный if
заявления, если хотите. Может быть, что-то вроде
int max_of_four(int a, int b, int c, int d)
{
if ( b > a )
{
if ( d > c )
{
if ( b > d )
return b;
else
return d;
}
else // d <= c
{
if ( b > c )
return b;
else
return c;
}
}
else // b <= a
{
// You got the idea...
}
}