// This program calculates and displays the area of a rectangle. #include <iostream> using namespace std; int main() { int length, width, area; cout << "This program calculates the area of a rectangle.n"; // Have the user input the rectangle's length and width cout << "What is the length of the rectangle? "; cin >> length; cout << "What is the width of the rectangle? "; cin >> width; // Compute and display the area area = length * width; cout << "The area of the rectangle is " << area << endl; return 0; }程式輸出結果:
This program calculates the area of a rectangle.
What is the length of the rectangle? 10
What is the width of the rectangle? 20
The area of the rectangle is 200.
cout << "What is the length of the rectangle?
cin >> length;
What is the length of the rectangle?
這就是告訴使用者應輸入矩形的長度。顯示提示之後,程式使用 cin 從鍵盤讀取值並將其儲存在 length 變數中。
cout << "What is the length of the rectangle? ";
cout <- "What is the length of the rectangle? ";
cin >> length;
cin —> length;
//This program illustrates what can happen when a // floating-point number is entered for an integer variable. #include <iostream> using namespace std; int main() { int intNumber; double floatNumber; cout << "Input a number. "; cin >> intNumber; cout << "Input a second number.n"; cin >> floatNumber; cout << "You entered: " << intNumber << " and " << floatNumber << endl; return 0; }程式輸出結果:
Input a number . 12.3
Input a second number. You entered: 12 and 0.3
// This program calculates and displays the area of a rectangle. #include <iostream> using namespace std; int main() { int length, width, area; cout << "This program calculates the area of a rectangle. n"; //Have the user input the rectangle1s length and width cout << "Enter the length and width of the rectangle " cout << "separated by a space. n"; cin >> length >> width; // Compute and display the area area = length * width; cout << "The area of the rectangle is " << area << endl; return 0; }程式輸出結果:
This program calculates the area of a rectangle.
Enter the length and width of the rectangle separated by a space.
10 20
cin >> length >> width;
在範例輸出中,使用者輸入 10 和 20,因此 10 儲存在 length 中,而 20 儲存在 width 中。注意,使用者在輸入數位時要用空格分隔數位。這樣 cin 才能知道每個數位的開始和結束位置。在每個數位之間輸入多少空格並不重要,需要注意的是,在最後一個數位輸入之後,必須按確認鍵。// This program demonstrates how cin can read multiple values // of different data types. #include <iostream> using namespace std; int main() { int whole; double fractional; char letter; cout << "Enter an integer, a double, and a character: "; cin >> whole >> fractional >> letter; cout << "whole: " << whole << endl; cout << "fractional: " << fractional << endl; cout << "letter: " << letter << endl; return 0; }程式輸出結果:
Enter an integer, a double, and a character: 4 5.7 b
whole: 4
fractional: 5.7
letter: b