はじめに
この実験では、C++ プログラミング言語で 2 つの数値を加算する基本プログラムを書く方法を学びます。また、C++ での変数宣言、初期化、入出力操作、および基本的な数学演算についても学びます。
この実験では、C++ プログラミング言語で 2 つの数値を加算する基本プログラムを書く方法を学びます。また、C++ での変数宣言、初期化、入出力操作、および基本的な数学演算についても学びます。
まず、ユーザー入力を格納するために、整数型の 2 つの変数 a
と b
を宣言します。また、変数 sum
を宣言して 0 で初期化します。
#include<iostream>
using namespace std;
int main()
{
//変数宣言
int a, b;
//変数宣言と初期化
int sum=0;
//...
}
cin
と cout
ステートメントを使用してユーザーから入力を受け取ります。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 つの数値 a
と b
を加算し、結果を変数 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;
}