Help us understand the problem. What is going on with this article?

C(とか)で四則演算の結果すら合わない

...という恥ずかしい検索を仕事中にテンパってやってしまった話。

実際にやらかしたミス

コード

before.cpp
#include <iostream>

#define IMAGE_HEIGHT 40
#define IMAGE_WIDTH 30
#define IMAGE_SIZE IMAGE_HEIGHT * IMAGE_WIDTH

#define BLOCK_HEIGHT 4
#define BLOCK_WIDTH 3
#define BLOCK_SIZE BLOCK_HEIGHT * BLOCK_WIDTH

int main(){
    std::cout << "image size: " << IMAGE_SIZE << std::endl;
    std::cout << "block size: " << BLOCK_SIZE << std::endl;
    std::cout << "# of blocks in a image: " << (IMAGE_SIZE / BLOCK_SIZE) << std::endl;
    return 0;
}

出力

image size: 1200
block size: 1200
# of blocks in a image: 900

(とりあえずの)修正

コード

#defineがやってるのは文字列置換なのでカッコを明記する。(thx. toori様)
* 修正前:IMAGE_HEIGHT * IMAGE_WIDTH / BLOCK_HEIGHT * BLOCK_WIDTH
* 修正後:((IMAGE_HEIGHT) * (IMAGE_WIDTH)) / ((BLOCK_HEIGHT) * (BLOCK_WIDTH))

after.cpp
#include <iostream>

#define IMAGE_HEIGHT 40
#define IMAGE_WIDTH 30
#define IMAGE_SIZE ((IMAGE_HEIGHT) * (IMAGE_WIDTH)) // !!!

#define BLOCK_HEIGHT 4
#define BLOCK_WIDTH 3
#define BLOCK_SIZE ((BLOCK_HEIGHT) * (BLOCK_WIDTH)) // !!!

int main(){
    std::cout << "image size: " << IMAGE_SIZE << std::endl;
    std::cout << "block size: " << BLOCK_SIZE << std::endl;
    std::cout << "# of blocks in a image: " << (IMAGE_SIZE / BLOCK_SIZE) << std::endl;
    return 0;
}

ただし、以上の書き方はC++の書き方としてかなり宜しくない模様。なぜ拡張子をcppにした
(コメント参照。thx. yumetodo様, ryoco様, amate様, y_itamoto様

出力

image size: 1200
block size: 12
# of blocks in a image: 100

教訓とか

  • 何となく使ってる構文とかが何やってるか正確に理解してないと事故る
  • こういう習慣で防げる系のミスは初学者のうちに潰したい
  • とりあえずおちつく
  • (追記)些細な出来事を書いたら結果的に勉強になった(ありがとうございます)
Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away