sizeofを使ってみた

※自分用メモ

この前書いたbowling scoreのコードで'sizeof'を使ってみては どうかと指摘を受けたので使ってみた。

#include <iostream>
#include <string>
using namespace std;

int bowlingScore[] =
{
    230, 222,206, 300, 220, 206    
};

int main()
{
    int i;
    int scoreTotal = 0;
    int gameCount = sizeof(bowlingScore) / sizeof(int);
    
    for(i = 0; i < gameCount; i++)
        scoreTotal += bowlingScore[i];
        
    cout << "Today's bowling average is: " << scoreTotal / gameCount << endl;
    
    return 0;
}

結果

Today's bowling average is 230.

さて、sizeofとは何かというと。。。 変数のサイズと形のサイズを取得する演算子です。
※得られるサイズの単位はバイト(他にもサイズなどを図れる「型」ある)
intの場合では小数点は出せない

小数点を出したいのであればfloatを使う
※下記のように型を変える場合は型キャストという
※でも型キャストは使うな!って言われてます。

#include <iostream>
#include <string>
using namespace std;

int bowlingScore[] =
{
    230, 222,206, 300, 220, 206    
};

int main()
{
    int i;
    int scoreTotal = 0;
    int gameCount = sizeof(bowlingScore) / sizeof(int);
    
    for(i = 0; i < gameCount; i++)
        scoreTotal += bowlingScore[i];
        
    cout << "Today's bowling score is: " << scoreTotal / (float)gameCount << endl;
    
    return 0;
}

結果

Today's bowling average is: 230.667