2019-07-28
AtCoder Beginner Contest 135 A
C++の基本的なところ、本読むより実際に書いた方が覚えられそうなので練習する。
最初に書いたコード
#include<iostream>
#include<string>
using namespace std;
int main() {
int n, m;
string message = "IMPOSSIBLE";
cin >> n >> m;
if ((n + m) % 2 == 0) {
cout << (n + m) / 2 << endl;
} else {
cout << message << endl;
}
}
他の回答をみて修正したコード
#include<iostream>
#include<string>
using namespace std;
int main() {
int n, m;
string message = "IMPOSSIBLE";
cin >> n >> m;
if ((n + m) & 1) cout << message << endl;
else cout << (n + m) / 2 << endl;
}
学んだこと
コンパイルと実行
g++ -o sample sample.cpp && ./sample
-o
は出力されるファイル(実行ファイル)の名前を指定するオブション
文字列は char 型の要素をもつ配列だが、string というモジュールを include すると string 型がつかえるようになる。
A ? B :C
で B と C の型は同じでなければならない。if 文の
{}
は省略できる。&
論理積を返す。X & 1
とすると、X の 1 の位が1なら1を返す。- つまり、2 で割った余りを求めるのと同じことができる。
ガチな方々は自作関数などを大量に用意してたりするので参考にしにくい。
main 関数の戻り値ってなんで int なの?
- 終了コードを返すから。
シングルクォーテーションは文字列リテラルを、ダブルクォーテーションは文字列へのポインタを表すらしい(理解が不正確かも)。