2 つの数を加算するプログラム

C++C++Beginner
今すぐ練習

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、C++ プログラミング言語で 2 つの数値を加算する基本プログラムを書く方法を学びます。また、C++ での変数宣言、初期化、入出力操作、および基本的な数学演算についても学びます。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("C++")) -.-> cpp/StandardLibraryGroup(["Standard Library"]) cpp(("C++")) -.-> cpp/BasicsGroup(["Basics"]) cpp(("C++")) -.-> cpp/IOandFileHandlingGroup(["I/O and File Handling"]) cpp/BasicsGroup -.-> cpp/variables("Variables") cpp/BasicsGroup -.-> cpp/data_types("Data Types") cpp/BasicsGroup -.-> cpp/operators("Operators") cpp/BasicsGroup -.-> cpp/strings("Strings") cpp/IOandFileHandlingGroup -.-> cpp/output("Output") cpp/IOandFileHandlingGroup -.-> cpp/user_input("User Input") cpp/IOandFileHandlingGroup -.-> cpp/files("Files") cpp/StandardLibraryGroup -.-> cpp/math("Math") subgraph Lab Skills cpp/variables -.-> lab-96120{{"2 つの数を加算するプログラム"}} cpp/data_types -.-> lab-96120{{"2 つの数を加算するプログラム"}} cpp/operators -.-> lab-96120{{"2 つの数を加算するプログラム"}} cpp/strings -.-> lab-96120{{"2 つの数を加算するプログラム"}} cpp/output -.-> lab-96120{{"2 つの数を加算するプログラム"}} cpp/user_input -.-> lab-96120{{"2 つの数を加算するプログラム"}} cpp/files -.-> lab-96120{{"2 つの数を加算するプログラム"}} cpp/math -.-> lab-96120{{"2 つの数を加算するプログラム"}} end

変数宣言

まず、ユーザー入力を格納するために、整数型の 2 つの変数 ab を宣言します。また、変数 sum を宣言して 0 で初期化します。

#include<iostream>

using namespace std;

int main()
{
    //変数宣言
    int a, b;

    //変数宣言と初期化
    int sum=0;

    //...
}

ユーザー入力

cincout ステートメントを使用してユーザーから入力を受け取ります。cout はユーザーにメッセージを表示するために使用され、cin はユーザーからの入力を受け付けるために使用されます。

cout << "\n\nWelcome to LabEx :-)\n\n\n";
cout << " =====  Program to add 2 numbers ===== \n\n";

cout << "Enter the first Number : ";
cin >> a;

cout << "\nEnter the second Number : ";
cin >> b;

2 つの数値の加算

2 つの数値 ab を加算し、結果を変数 sum に格納します。

//Adding the two numbers
sum = a + b;

結果を表示する

cout ステートメントを使用して結果をユーザーに表示します。

//displaying the final output (sum)
cout << "\nAddition of the two numbers is : " << sum;

プログラムをコンパイルして実行する

ターミナルで以下のコマンドを使用してプログラムをコンパイルします。

g++ ~/project/main.cpp -o main

ターミナルで以下のコマンドを使用してプログラムを実行します。

./main

出力を確認する

プログラムを実行した後、ターミナルに以下の出力が表示されるはずです。

Welcome to LabEx :-)


 =====  Program to add 2 numbers =====

Enter the first Number : 10

Enter the second Number : 20

Addition of the two numbers is : 30

まとめ

この実験では、2 つの数を加算する基本的な C++ プログラムを書く方法を学びました。また、C++ における変数宣言、初期化、ユーザー入出力、および基本的な数学演算についても学びました。これで、他の数学演算を試したり、プログラムを自分のニーズに合わせて修正したりすることができます。

以下は main.cpp ファイルのコード全体です。

#include<iostream>

using namespace std;

int main()
{
    //変数宣言
    int a, b;

    //変数宣言と初期化
    int sum=0;

    //ユーザー入力を受け取る
    cout << "\n\nWelcome to LabEx :-)\n\n\n";
    cout << " =====  Program to add 2 numbers ===== \n\n";

    cout << "Enter the first Number : ";
    cin >> a;

    cout << "\nEnter the second Number : ";
    cin >> b;

    //2 つの数を加算する
    sum = a + b;

    //最終出力(合計)を表示する
    cout << "\nAddition of the two numbers is : " << sum;

    return 0;
}