読み込んだ月の季節を表示 (論理演算子)

明解C言語 入門編 > 3. プログラムの流れと分岐 >

読み込んだ月の季節を表示 (論理演算子)

C


#include <stdio.h>
int main(int argc, char* argv[])
{
int month;

printf("何月ですか:");
scanf("%d", &month);

if (3 <= month && month <= 5)
puts("春です。");
else if (6 <= month && month <= 8)
puts("夏です。");
else if (9 <= month && month <= 11)
puts("秋です。");
else if (month == 1 || month == 2 || month == 12)
puts("冬です。");
else
puts("そんな月はありませんよ!!");

return 0;
}

実行結果


R:\>lesson022\project1.exe
何月ですか:5
春です。

R:\>lesson022\project1.exe
何月ですか:8
夏です。

Delphi


program Project1;

{$APPTYPE CONSOLE}

uses
SysUtils;
var
month: Integer;
begin
write('何月ですか:');
read(month);

if (3 <= month) and (month <= 5) then
writeln('春です。')
else if (6 <= month) and (month <= 8) then
writeln('夏です。')
else if (9 <= month) and (month <= 11) then
writeln('秋です。')
else if (month = 1) or (month = 2) or (month = 12) then
writeln('冬です。')
else
writeln('そんな月はありませんよ!!');
end.

実行結果


S:\>lesson022\project1.exe
何月ですか:5
春です。

S:\>lesson022\project1.exe
何月ですか:8
夏です。

Perl
print "何月ですか:";
chomp($month = <STDIN>);

if (3 <= $month && $month <= 5)
{
    printf "春です。\n";
}
elsif (6 <= $month && $month <= 8)
{
    printf "夏です。\n";
}
elsif (9 <= $month && $month <= 11)
{
    printf "秋です。\n";
}
elsif($month == 1 || $month == 2 || $month == 12)
{
    printf "冬です。\n";
}
else
{
    printf "そんな月はありませんよ!!\n";
}

実行結果

L:\>perl lesson_03_022.pl
何月ですか:5
春です。

L:\>perl lesson_03_022.pl
何月ですか:8
夏です。

Ruby
print "何月ですか:"
month = STDIN.gets.chomp.to_i

if (3 <= month && month <= 5)
    puts "春です。"
elsif (6 <= month && month <= 8)
    puts "夏です。"
elsif (9 <= month && month <= 11)
    puts "秋です。"
elsif(month == 1 || month == 2 || month == 12)
    puts "冬です。"
else
    puts "そんな月はありませんよ!!"
end

if ((3..5) === month)
    puts "春です。"
elsif ((6..8) === month)
    puts "夏です。"
elsif ((9..11) === month)
    puts "秋です。"
elsif((1..12) === month)
    puts "冬です。"
else
    puts "そんな月はありませんよ!!"
end

実行結果

L:\>ruby l:\lesson_03_022.rb
何月ですか:5
春です。
春です。

L:\>ruby l:\lesson_03_022.rb
何月ですか:8
夏です。
夏です。