ABC三只小猪称重的代码怎么写
时间: 2023-12-01 10:39:51 浏览: 80
abc.rar_ABC_ABC算法_ABC算法代码_c教学演示
可以使用以下两种方法来编写ABC三只小猪称重的代码:
方法一:使用if嵌套语句
```
#include <iostream>
using namespace std;
int main() {
int a, b, c;
cout << "请输入小猪A的体重:";
cin >> a;
cout << "请输入小猪B的体重:";
cin >> b;
cout << "请输入小猪C的体重:";
cin >> c;
if (a >= b && a >= c) {
cout << "小猪A最重" << endl;
if (b >= c) {
cout << "小猪B次重,小猪C最轻" << endl;
} else {
cout << "小猪C次重,小猪B最轻" << endl;
}
} else if (b >= a && b >= c) {
cout << "小猪B最重" << endl;
if (a >= c) {
cout << "小猪A次重,小猪C最轻" << endl;
} else {
cout << "小猪C次重,小猪A最轻" << endl;
}
} else {
cout << "小猪C最重" << endl;
if (a >= b) {
cout << "小猪A次重,小猪B最轻" << endl;
} else {
cout << "小猪B次重,小猪A最轻" << endl;
}
}
return 0;
}
```
方法二:使用三目运算符
```
#include <iostream>
using namespace std;
int main() {
int a, b, c;
cout << "请输入小猪A的体重:";
cin >> a;
cout << "请输入小猪B的体重:";
cin >> b;
cout << "请输入小猪C的体重:";
cin >> c;
int max = (a > b ? (a > c ? a : c) : (b > c ? b : c));
int min = (a < b ? (a < c ? a : c) : (b < c ? b : c));
int mid = a + b + c - max - min;
cout << "小猪" << (max == a ? "A" : (max == b ? "B" : "C")) << "最重" << endl;
cout << "小猪" << (mid == a ? "A" : (mid == b ? "B" : "C")) << "次重" << endl;
cout << "小猪" << (min == a ? "A" : (min == b ? "B" : "C")) << "最轻" << endl;
return 0;
}
```
阅读全文