0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C++入門 AtCoder Programming Guide for beginners (APG4b)のEX6 - 電卓をつくろう

Last updated at Posted at 2023-01-24

読んで欲しい人

・未来の私。(実は2回目)
・電卓を作りたい人
・プログラミングを詳しい方。

注意

・C++入門 AtCoder Programming Guide for beginners (APG4b)のEX6 - 電卓をつくろう
のネタバレがあります。

問題文

EX6 - 電卓をつくろう

ACしたコード

#include <bits/stdc++.h>
using namespace std;

int main() {
	int A, B;
	string op;
	cin >> A >> op >> B;

	if (op == "+") {
	cout << A + B << endl;
	} else if (op == "-") {
	cout << A - B << endl;
	} else if (op == "*") {
	cout << A * B << endl;
	} else if (op == "/" && B != 0) {
	cout << A / B << endl;
	} else {
	cout << "error" << endl;
	}
}

理解できなかったところ1

・電卓で0で割るとエラーになる事を認識してなかった。0で割り算すると、、、の記事

//初手のコード(部分)
      else if (op == "/") {
          cout << A / B << endl;
    } else if (op == "/" && B == 0) {
          cout << "error" << endl;
	}

この書き方だとテストケースで 100 / 0 が与えられた場合

Floating point exception (core dumped)

このようなエラーになる。
(このエラー文を詳しく知りたいけど調べてみたら沼になったので後回しにする。)
(多分、浮動小数点例外だと思うけど自信がない)

理解できなかったところ2

・条件分岐の判定の順番
初手のコード(部分)で判定されているのは最初の else だけでは?
と思ったので else の順番を入れ替えたらACできた 笑

#include <bits/stdc++.h>
using namespace std;

int main() {
	int A, B;
	string op;
	cin >> A >> op >> B;

	if (op == "+") {
    	cout << A + B << endl;
	} else if (op == "-") {
    	cout << A - B << endl;
	} else if (op == "*") {
    	cout << A * B << endl; 
	} else if (op == "/" && B == 0) { //ここと
        cout << "error" << endl;
    } else if (op == "/") {           //ここの順番を入れ替えた
        cout << A / B << endl;
    } else {
    	cout << "error" << endl;
	}
}

順番を入れ替えると判定される順番も変更されるから
解説と異なるコードだけどACになる。

#include <bits/stdc++.h>
#include <iostream>

↑の使い分けがわからないので調べ中

参考にした記事まとめ

0で割り算すると、、、の記事

0
0
0

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?