在 C++ 中對兩個數字進行加法


加法是一種基本的算術運算。對兩個數字進行加法的程式執行兩個數字的加法運算,然後將它們的和顯示在螢幕上。

以下是演示對兩個數字進行加法的程式:

示例

 線上演示

#include <iostream>
using namespace std;
int main() {
   int num1=15 ,num2=10, sum;
   sum = num1 + num2;
   cout<<"Sum of "<<num1<<" and "<<num2<<" is "<<sum;
   return 0;
}

輸出

Sum of 15 and 10 is 25

在上述程式中,兩個數字的和(即 15 和 10)儲存在變數 sum 中。

sum = num1 + num2;

然後使用 cout 物件將其顯示在螢幕上。

cout<<"Sum of "<<num1<<" and "<<num2<<" is "<<sum;

以下是使用陣列儲存兩個數字及其和的程式:

示例

 線上演示

#include <iostream>
using namespace std;
int main() {
   int a[3];
   a[0]=7;
   a[1]=5;
   a[2]=a[0] + a[1];
   cout<<"Sum of "<<a[0]<<" and "<<a[1]<<" is "<<a[2];
   return 0;
}

輸出

Sum of 7 and 5 is 12

在上述程式中,要進行加法的數字儲存在陣列的 0 和 1 索引中。

a[0]=7;
a[1]=5;

然後,將和儲存在陣列的 2 索引中。

a[2]=a[0] + a[1];

使用 cout 物件將和顯示在螢幕上。

cout<<"Sum of "<<a[0]<<" and "<<a[1]<<" is "<<a[2];

更新於: 2020-6 月 23 日

12K+ 瀏覽量

開啟您的 職業生涯

獲得完成課程的認證

開始
廣告
© . All rights reserved.