这段代码中使用函数找到最大的四个数字是什么错?这是一个来自Hackerrank c++实践的问题。请给出解决方案。
这是我得到的错误:
Solution.cpp: In function ' int max(int, int, int, int) ':解决方案:cpp:21:5:错误:期望'}'在' else '之前else {cout <<"bgreatest"& lt; & lt;endl;} ^~~~ Solution.cpp:9:16: note: to match this' {' if (a>b) {^ Solution.cpp:22:5:错误:没有返回语句函数返回非void [-Werror=return-type]} ^在全局作用域中:Solution.cpp:23:1: error: expected声明^ cc1plus:一些警告被视为错误
#include <iostream>
#include <stdio.h>
using namespace std;
/*
Add `int max_of_four(int a, int b, int c, int d)` here.
*/
int max(int a, int b, int c, int d)
{
if (a > b) {
if (a > c) {
if (a > d) {
cout << "a is greatest" << endl;
}
else {
cout << "d is greatest" << endl;
}
}
else {
cout << "c is greatest" << endl;
}
else { cout << "b is greatest" << endl; }
}
}
int main()
{
int a, b, c, d;
cin >> a >> b >> c >> d;
int ans = max(a, b, c, d);
cout << ans;
return 0;
}
错误在第22行:你把else放在if括号里面而不是放在外面,这就是为什么你得到编译错误:
#include <iostream>
#include <stdio.h>
using namespace std;
/*
Add `int max_of_four(int a, int b, int c, int d)` here.
*/
int max(int a, int b, int c, int d)
{
if (a >= b && a >= c && a >= d) return a;
if (b >= a && b >= c && b >= d) return b;
if (c >= b && c >= a && c >= d) return c;
return d;
}
int main()
{
int a, b, c, d;
cin >> a >> b >> c >> d;
int ans = max(a, b, c, d);
cout << ans;
return 0;
}
这个函数将返回4个int中的最大值。
我是这样做的:
#include <iostream>
int max(int a, int b)
{
return a >= b ? a : b;
}
int max(int a, int b, int c, int d)
{
return max(max(a, b), max(c, d)); // Only 3 comparisons
}
int main()
{
int a, b, c, d;
std::cin >> a >> b >> c >> d;
std::cout << max(a, b, c, d);
}
这里有两点:
- 避免使用
using namespace std;
,因为它会污染全局命名空间。 - 在这个版本中,只有3个比较(而不是可能的12,如果你比较每个数字与所有其他的)。
-
Hackerrank不接受四个if,所以我在max函数中使用了if else和else。
-
在原始代码中,我的错误是我没有返回任何东西到我的函数,这是通过在max函数中返回a, b, c, d来纠正的。
#include <iostream> #include <stdio.h> using namespace std; int max(int a, int b, int c, int d) { if (a >= b && a >= c && a >= d) {return a;} else if (b >= a && b >= c && b >= d) return b; else if (c >= b && c >= a && c >= d) return c; else return d; } int main() { int a, b, c, d; cin >> a >> b >> c >> d; int ans = max(a, b, c, d); cout << ans; return 0; }
#include <iostream>
#include <cstdio>
using namespace std;
/*
Add `int max_of_four(int a, int b, int c, int d)` here.
*/
int max_of_four(int a, int b, int c, int d)
{
int biggest = a;
if (b > biggest) biggest = b;
if (c > biggest) biggest = c;
if (d > biggest) biggest = d;
return biggest;
}
int main() {
int a, b, c, d;
scanf("%d %d %d %d", &a, &b, &c, &d);
int ans = max_of_four(a, b, c, d);
printf("%d", ans);
return 0;
}