C++ 程式列印使用者輸入的數字


物件“cin”和“cout”分別用於 C++ 中的輸入和輸出。cin 是 istream 類的例項,並連線到標準輸入裝置,例如鍵盤。cout 是 ostream 類的例項,並連線到標準輸出裝置,例如顯示屏。

列印使用者輸入數字的程式如下所示:

示例

 線上演示

#include <iostream>
using namespace std;
int main() {
   int num;
   cout<<"Enter the number:\n";
   cin>>num;
   cout<<"The number entered by user is "<<num;
   return 0;
}

輸出

Enter the number: 5
The number entered by user is 5

在上面的程式中,使用者使用 cin 物件輸入數字。

cout<<"Enter the number:\n";
cin>>num;

然後使用 cout 物件顯示該數字。

cout<<"The number entered by user is "<<num;

使用者輸入多個數字的一種方法是使用陣列。這在下面的程式中進行了演示:

示例

 線上演示

#include <iostream>
using namespace std;
int main() {
   int a[5],i;
   cout<<"Enter the numbers in array\n";
   for(i=0; i<5; i++)
   cin>>a[i];
   cout<<"The numbers entered by user in array are ";
   for(i=0; i<5; i++)
   cout<<a[i]<<" ";
   return 0;
}

輸出

Enter the numbers in array
5 1 6 8 2
The numbers entered by user in array are 5 1 6 8 2

在上面的程式中,for 迴圈用於訪問使用者的所有陣列元素。對於 for 迴圈的每次迭代,使用 cin 物件訪問具有相應索引的陣列元素。

for(i=0; i<5; i++)
cin>>a[i];

之後,使用相同的 for 迴圈概念顯示所有陣列元素。

for(i=0; i<5; i++)
cout<<a[i]<<" ";

更新於: 2020-06-23

5K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.