Menu
CoddyTech

ブール論理と等価性

Coddyの「C++開発者のためのC#」コースのレッスン 8/48。

C++では、数値やポインターからboolへの文脈依存の変換が可能です。C#の通常の条件式では、数値を条件として扱うのではなく、boolが必要です。ポインターや個数の真偽値テストをそのまま移植するのではなく、明示的な比較を使用してください。

C#の条件式には、任意の数値やコレクションではなく、bool式が必要です。&&と||は短絡評価を行い、!はブール値を否定します。文字列のオペランドに対するString ==はテキストの内容を比較します。一方、通常のクラス参照では、その型が動作を変更しない限り、参照の同一性が比較されます。

C++の参照コード

#include <algorithm>
#include <array>
#include <cctype>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;

int main() {
bool active=true;
cout << (20>=18 && active ? "true" : "false") << "\n";
}

Main内のC#文

bool active = true;
Console.WriteLine((20 >= 18 && active) ? "true" : "false");

これらは、要点を絞った学習用の抜粋です。課題ファイルには実行可能な完全なラッパーが含まれており、上記のスニペットには関連する宣言と文が示されています。

参照出力:

true

C#の出力:

true
challenge icon

チャレンジ

簡単

年齢と小文字のtrue/falseフラグを別々の行で読み取ります。18歳以上の活動中の人の場合にのみtrueを返してください。

ロック解除されたC#ファイルを編集してください。表示されているロック済みのMain.csは説明されている行を読み取り、Exercise.Solveを呼び出し、入力が変更されていないことを確認して、最後に改行を1つ付けて結果を出力します。宣言済みのAPIを維持してください。2つ目のMainを追加したり、診断出力を出したりしないでください。

自分で試してみよう

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = I(input[0]); string before0=Snapshot(a0);
var a1 = input[1] == "true"; string before1=Snapshot(a1);

var result = Exercise.Solve(a0,a1);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
if (Snapshot(a1) != before1) throw new Exception("Input mutation");
Console.WriteLine(result ? "true" : "false");
}
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

C++開発者のためのC#のすべてのレッスン

自分で練習してみよう: C#オンラインコンパイラ