불리언 논리와 같음 비교
Coddy의 C++ 개발자를 위한 C# 코스 레슨. 48개 중 8번째.
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");이 내용은 핵심만 다루는 학습용 발췌문입니다. 과제 파일에는 완전한 실행용 래퍼가 포함되어 있으며, 위 코드 조각은 관련 선언과 문을 보여 줍니다.
참조 출력:
trueC# 출력:
true챌린지
쉬움나이와 소문자로 된 true/false 플래그를 각각 별도의 줄에서 읽으세요. 나이가 18세 이상이고 활성 상태인 사람에 대해서만 true를 반환하세요.
잠금 해제된 C# 파일을 수정하세요. 잠겨 있어 화면에 표시되는 Main.cs는 설명된 줄을 읽고, Exercise.Solve를 호출하고, 입력이 변경되지 않았는지 확인한 다음 결과를 마지막 줄바꿈 하나와 함께 출력합니다. 선언된 API를 유지하세요. 두 번째 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");
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C++ 개발자를 위한 C#의 모든 레슨
직접 연습해 보세요: 온라인 C# 컴파일러