以下の問題をC#をつかって解答せよ。
Q.
コンソールに2つの整数を2,3のようにカンマ区切りで入力する。
その2つの整数が偶数と奇数の組み合わせになっている場合にはOK,そうでない場合にはNGと出力するプログラムを作成せよ。
[実行例1]
3,5[enter]
NG
[実行例2]
4,5[enter]
OK
[解答例」
using System;
namespace Lesson1
{
class Program
{
static void Main(string[] args)
{
var data = Console.ReadLine().Split(',');
var d1 = int.Parse(data[0]);
var d2 = int.Parse(data[1]);
Console.WriteLine((d1 + d2) % 2 == 0 ? "NG": "OK");
}
}
}
Q.
上の問いを複数の入力に対しても適用させよ。
[実行例1]
1,3,5,3[enter]
NG
[実行例2]
2,2,1[enter]
OK
using System;
namespace LessonDelegate
{
class MainClass
{
public static void Main(string[] args)
{
var data = Console.ReadLine().Split(',');
bool hasEven = false;
bool hasOdd = false;
foreach(var n in data){
if(int.Parse(n) % 2==0){
hasEven = true;
}else{
hasOdd = true;
}
if(hasEven && hasOdd){
break;
}
}
Console.WriteLine((hasEven && hasOdd) ? "OK": "NG");
}
}
}
Q.
コンソールに文字列を入力する。その文字列に,と.が混在する場合には以下のルールで統一する。
1.数が多い方で統一する。
2.数が同じ場合には,で統一する。
[実行例1]
a,b,c.d[enter]
a,b,c,d
[実行例2]
aa.bb.cc,dd[enter]
aa.bb.cc.dd
[実行例3]
abcd[enter]
abcd
[実行例4]
a.b.c,d,[enter]
a,b,c,d,
[実行例5]
,..a.[enter]
…a.
[解答例]
using System;
using System.Linq;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
var str = Console.ReadLine();
if (str.Contains(',') && str.Contains('.'))
{
var cCount = str.Split(',').Length;
var pCount = str.Split('.').Length;
if (cCount >= pCount)
{
str = str.Replace('.', ',');
}
else
{
str = str.Replace(',', '.');
}
}
Console.WriteLine(str);
}
}
}


コメント