Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ チャレンジ:変数の型修飾子 | セクション
C++のデータ型

チャレンジ:変数の型修飾子

メニューを表示するにはスワイプしてください

キーワード short および long は型修飾子。データ型のサイズや範囲を変更するために使用。新しいデータ型を作成するのではなく、既存の型の特性を変更。

type_modifiers.h

type_modifiers.h

1234567
// `short` is used for variables // That require smaller range of values. short int small_range_integer_variable; // `long` is used for variables // That require a larger range of values. long int large_range_integer_variable;

値が確実に小さいことが分かっている場合がある。例えば、ユーザーの年齢を保存する場合、その値は255を超えない。このような値は8ビットに収まる。

main.cpp

main.cpp

12345678910
#include <iostream> int main() { short int small_number = 45; long int large_number = 4000000000; std::cout << "Small number: " << small_number <<std:: endl; std::cout << "Large number: " << large_number << std::endl; }

これらの型修飾子は、型のサイズを変更する役割を持つ。intは4バイトを使用し、short intは2バイト、long intは8バイトのメモリを使用する。

Note
注意

より短い構文も利用可能で、どちらも使用できる:

  • short は short int と同等;
  • long は long int と同等;

大きな値を格納するには、long(long int)の使用が必要。対照的に、short(short int)を使用すると、より少ないメモリで済む。ただし、その分範囲は狭くなる。各型が保持できる範囲を示す表は以下の通り。

タスク

スワイプしてコーディングを開始

calculateEnergyConsumption 関数は、1人あたりの小さな値を大きな人口で掛け算し、オーバーフローを防ぎます。

  1. averageConsumption を short int 型で保存。
  2. cityPopulation を int 型で保存。
  3. それらを掛け算し、結果を long int 型の totalConsumption に保存。
  4. totalConsumption を返却。
  5. 関数内で averageConsumption および cityPopulation の値は変更しないこと。

averageConsumption 関数内で cityPopulation と calculateEnergyConsumption の値を変更しないでください。

解答

Switch to desktop実践的な練習のためにデスクトップに切り替える下記のオプションのいずれかを利用して、現在の場所から続行する
すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1. 章 3
single

single

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

some-alt