💻補足のソースたち
🟦関数と引数
- "Main.cpp"
#include <iostream> #include <vector> #include <iomanip> // std::setprecision // 関数のプロトタイプ宣言 float getAverage(float score[], int num); //平均値を計算して返す char getRank(float score[], int num); //80点以上→A、60点以上→B、40点以上→C、それ以下→D int main() { //std::vector<double> scores(3); //(N)ってやればN個の要素を持つ配列が作れる float scores[3]; std::cout << "3科目の点数を入力してください(例: 80 70 90)> "; for (int i = 0;i < 3; i++) std::cin >> scores[i]; double avg = getAverage(scores, 3); char rank = getRank(scores, 3); std::cout << std::fixed << std::setprecision(1);//小数点以下1桁まで表示 std::cout << "平均点: " << avg << " 点" << std::endl << "評価: " << rank << std::endl; } //関数の定義 float getAverage(float score[3], int num) { double sum = 0; for (int i = 0; i < num; ++i) { sum += score[i]; } return sum / num; } char getRank(float score[3], int num) { float avg = getAverage(score, num); if (avg >= 80) { return 'A'; } else if (avg >= 60) { return 'B'; } else if (avg >= 40) { return 'C'; } else { return 'D'; } }
🟦関数と引数とポインタとアドレス📮
- "Main.cpp"
#include <iostream> #include <iomanip> // std::setprecision int add(int a, int b) { a += 2; b += 3; return a + b; } int addPointer(int* a, int* b) { *a += 2; *b += 3; return *a + *b; } void addPointer2(int a, int b, int* aa, int* bb, int* ans) { a += 2; b += 3; *aa = a; *bb = b; *ans = a + b; } int main() { int a = 3, b = 5; int newA, newB, newAns; addPointer2(a, b, &newA, &newB, &newAns); std::cout << "a: " << a << ", b: " << b << ", newA: " << newA << ", newB: " << newB << ", newAns: " << newAns << std::endl; //int ans = add(a, b); //int ans = addPointer(&a, &b); //std::cout << "a: " << a << ", b: " << b << // ", ans: " << ans << std::endl; return 0; }
🟦stringの中の文字
- "Main.cpp"
#include <iostream> #include <string> using std::string; using std::cin; using std::cout; using std::endl; int CountWords(std::string str) { for (int i = 0;i < str.size();i++) { cout << str[i] << endl; } return str.size(); } int main() { string inputStr; std::cout << "文字列を入力してください: "; cin >> inputStr; int wordCount = CountWords(inputStr); cout << "単語数: " << wordCount << endl; }