LoginSignup
0

More than 3 years have passed since last update.

AtCoder Beginner Contest 135 A

Posted at

C++の基本的なところ、本読むより実際に書いた方が覚えられそうなので練習する。

[https://atcoder.jp/contests/abc135/tasks/abc135_a:title]

最初に書いたコード

#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の位が{0, 1}なら{0, 1}を返す。
    • つまり、2で割った余りを求めるのと同じことができる。
  • ガチな方々は自作関数などを大量に用意してたりするので参考にしにくい。

  • main関数の戻り値ってなんでintなの?

    • 終了コードを返すから。
  • シングルクォーテーションは文字列リテラルを、ダブルクォーテーションは文字列へのポインタを表すらしい(理解が不正確かも)。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0