関数とは何ですか?
メニューを表示するにはスワイプしてください
関数は、プログラミングにおける基本的な構成要素。特定のタスクを実行するために設計された再利用可能なコードのブロック。関数を使用することで、コードがより整理され、可読性が向上し、保守が容易になる。関数によって、大規模で複雑なプログラムをより小さく、管理しやすいサブルーチンに分割可能。
main.cpp
1234int main() // `main` is the name of a function { return 0; }
注意
mainという名前はC++言語によってすでに予約されている。そのため、この名前で関数を宣言すると、コンパイラはエラーを生成する。
関数の作成には、特定のタスクを実行し、プログラムにシームレスに統合するためのいくつかの重要な手順が含まれます。関数は、戻り値の型、名前、(必要に応じて)パラメータ、およびロジックが記述される本体で構成されます。
get_bank_name.h
123456// Returns the name of the bank std::string get_bank_name() // Function declaration with return type and name { std::string bank_name = "Future Savings Bank"; // Store bank name return bank_name; // Return it to the caller }
関数を作成した後、次のステップはその関数を呼び出すことです。関数を呼び出すことで、その中のコードが実行され、(値を返す場合は)その結果を利用できます。
main.cpp
1234567891011121314#include <iostream> #include <string> // Function to return the name of the bank std::string get_bank_name() { std::string bank_name = "Future Savings Bank"; return bank_name; // Return the name of the bank } int main() { std::cout << "Name of the bank: " << get_bank_name() << std::endl; }
通貨の換算は、特に国際取引や旅行において一般的な現実の作業です。関数を作成することで、このプロセスを簡素化し、換算処理を再利用可能かつ効率的にすることができます。
main.cpp
123456789101112131415#include <iostream> // Function to convert USD to Euros double convert_usd_to_eur(double usd_amount) { const double exchange_rate = 0.91; double euros = usd_amount * exchange_rate; return euros; } int main() { double usd = 100.0; // Amount in USD std::cout << usd << " USD = " << convert_usd_to_eur(usd) << " EUR" << std::endl; }
すべて明確でしたか?
フィードバックありがとうございます!
セクション 5. 章 1
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 5. 章 1