C++ 例 - 3つの数値の最大値を判定
画面から3つの数字を入力し、最大の数を見つけます。
例 - ifを使用
#include <iostream>
using namespace std;
int main()
{
float n1, n2, n3;
cout << "3つの数値を入力してください:";
cin >> n1 >> n2 >> n3;
if(n1 >= n2 && n1 >= n3)
{
cout << "最大数は:" << n1;
}
if(n2 >= n1 && n2 >= n3)
{
cout << "最大数は:" << n2;
}
if(n3 >= n1 && n3 >= n2) {
cout << "最大数は:" << n3;
}
return 0;
}
上記のプログラムの実行出力結果は:
请输入三个数: 2.3 8.3 -4.2 最大数为: 8.3
例 - if...elseを使用
#include <iostream>
using namespace std;
int main()
{
float n1, n2, n3;
cout << "3つの数値を入力してください:";
cin >> n1 >> n2 >> n3;
if((n1 >= n2) && (n1 >= n3))
cout << "最大数は:" << n1;
else if ((n2 >= n1) && (n2 >= n3))
cout << "最大数は:" << n2;
else
cout << "最大数は:" << n3;
return 0;
}
上記のプログラムの実行出力結果は:
请输入三个数,以空格分隔: 2.3 8.3 -4.2 最大数为: 8.3
例 - ネストされたif...elseを使用
#include <iostream>
using namespace std;
int main()
{
float n1, n2, n3;
cout << "3つの数値を入力してください:";
cin >> n1 >> n2 >> n3;
if (n1 >= n2)
{
if (n1 >= n3)
cout << "最大数は:" << n1;
else
cout << "最大数は:" << n3;
}
else
{
if (n2 >= n3)
cout << "最大数は:" << n2;
else
cout << "最大数は:" << n3;
}
return 0;
}
上記のプログラムの実行出力結果は:
请输入三个数,以空格分隔: 2.3 8.3 -4.2 最大数为: 8.3その他の拡張