程序5.4
1 #include<iostream> 2 using namespace std; 3 4 const int Size = 16; 5 6 void main() { 7 long long factorials[Size]; 8 factorials[1] = factorials[0] = 1LL; 9 for (int i = 2; i < Size; i++) 10 { 11 factorials[i] = i*factorials[i - 1]; 12 } 13 for (int i = 0; i < Size; i++) 14 { 15 cout << i << "!=" << factorials[i] << endl; 16 } 17 system("pause"); 18 }
factorials阶乘函数
递增/递减运算符和指针
前缀递增递减和*优先级相同,从右到左;
后缀递增递减比前缀优先级高,从左到右。
比如
int arr[5] = { 1,3,5,7,9 }; int *p = arr;
*++p:p先自+,然后*p,最终为3
++*p:先*,然后再++,最终为2
*p++:值为arr[0],即1,该语句执行完毕后,p指向arr[1](因为后缀优先级高,所以等价于*(p++),自增p并返回自增之前指向的值)
程序5.8
1 #include<iostream> 2 using namespace std; 3 4 void main() { 5 double sum = 0.0, number; 6 cout << "The Amazing Accounto will sum and average five numbers for you.." << endl; 7 cout << "Please enter five values: " << endl; 8 for (int i = 1; i < 6; i++) 9 { 10 cout << "Value " << i << ":"; 11 cin >> number; 12 sum += number; 13 } 14 cout << "Sum=" << sum << endl; 15 cout << "Average=" << sum/5 << endl; 16 17 system("pause"); 18 }
程序5.9(反转字符串)
1 #include<iostream> 2 #include<string> 3 using namespace std; 4 5 void main() { 6 cout << "Enter a word:"; 7 string word; 8 cin >> word; 9 char tmp;//tmp也可以在循环体内部定义,这样的话将在每次循环中都分配和释放,效率稍微慢一点 10 for (int j = 0,i=word.size()-1; j < i; ++j,--i)//word.size()不包括‘