1. 程式人生 > >C++編程基礎一 28-編程練習一

C++編程基礎一 28-編程練習一

dex turn 運算 控制臺應用程序 number 數字 代碼 amp 報告

  1 // 28-編程練習一.cpp: 定義控制臺應用程序的入口點。
  2 //
  3 
  4 #include "stdafx.h"
  5 #include <iostream>
  6 #include <climits>
  7 #include <array>
  8 #include <string>
  9 #include <math.h>
 10  
 11 using namespace std;
 12 
 13 int main()
 14 {
 15   //1.下面代碼會打印什麽內容?
 16     int i;
17 for (int i = 0; i < 5; i++) 18 cout << i; 19 cout << endl; 20 //答:01234 21 22 //2.下面代碼會打印什麽內容 23 int j; 24 for (j = 0; j < 11; j += 3) 25 cout << j; 26 cout << endl << j << endl; 27 //答:0369 28 // 12
29 // 30 31 //3.下面代買會打印什麽內容? 32 int f = 5; 33 while (++f < 9) //單獨使用++i和i++時候沒有區別,但是放在表達式中時候會有區別。 34 cout << f++ << endl; //i++會先使用i的值進行表達式運算,結束後i再自增,++i會先自增再進行表達式的運算。 35 //答:6 36 // 8 37 // 38 39 //4.下面代碼會打印什麽內容? 40 int k = 8; 41
do 42 cout << "k=" << k << endl; 43 while (k++ < 5); 44 //答: 45 //k=8 46 // 47 48 //5、編寫一個打印 1 2 4 8 16 32 64 的for循環 49 //方法一:do while循環 50 int temp = 1; 51 int index =0; 52 do 53 { 54 cout << temp << endl; 55 temp *= 2; 56 index++; 57 } while (index<7); 58 59 //方法二:for 循環 60 int temp2 = 1; 61 for (int i=0;i<7;i++) 62 { 63 temp2 = int(pow(2, i)); 64 cout << temp2 << endl; 65 } 66 //方法三 :先循環存儲,後遍歷輸出。 67 array<int, 7> array1{}; 68 for (int i = 0; i<7; i++) 69 { 70 array1[i]= pow(2, i); 71 } 72 73 for (int temp : array1) //只能取temp對應的值,不能設置值,要想設置temp對應數組中的值就用int& temp : array1 74 { 75 cout << temp << endl; 76 } 77 78 //方法四:最簡單的 79 for (int i = 1; i <= 64; i *= 2) 80 { 81 cout << i << endl; 82 } 83 84 //6.編寫一個程序,讓用戶輸入兩個整數,輸出這兩個整數之間(包括這兩個整數)所有整數的和。比如2 5裏面有2 4 5 所有整數和為11 85 86 int num1; 87 int num2; 88 int num3=0; 89 90 cout << "請輸入兩個整數:"<<endl; 91 cin >> num1; 92 cin >> num2; 93 cout << "輸入的兩個數為:"<<num1 << " " << num2<<endl; 94 if (num1 > num2) 95 { 96 int temp; 97 temp = num1; 98 num1 = num2; 99 num2 = temp; 100 } 101 for (int i = num1; i <= num2; i++) 102 { 103 cout << i << " "; 104 num3 = num3 + i; 105 } 106 cout <<"他們的和為:" <<num3 << endl; 107 108 //7.編寫一個程序,讓用戶可以持續輸入數字,每次輸入數字的時候,報告當前所有輸入的和。當用戶輸入0的時候,程序結束。 109 //方法一: 110 int alNum=0; 111 int inpNum=2; 112 while (inpNum!=0) 113 { 114 cout << "請輸入數字:"<<endl; 115 cin >> inpNum; 116 alNum += inpNum; 117 cout << "當前輸入的和為:" << alNum << endl;; 118 } 119 //方法二: 120 float total = 0; 121 while (true) 122 { 123 cout << "請輸入一個數字:"; 124 float number; 125 cin >> number; 126 if (number == 0) 127 { 128 break; //break語句跳出循環 129 } 130 total += number; 131 cout << "當前所有輸入的和為:" << total << endl; 132 } 133 134 int t; 135 cin >> t; 136 return 0; 137 }

C++編程基礎一 28-編程練習一