C++ 考级试题
1. 输出保留指定小数的浮点数: cout.precision()
1 #include "iostream" 2 using namespace std; 3 int main() 4 { 5 double num; 6 cin >> num; 7 8 // 9 cout.precision(12); 10 cout << fixed << num; 11 12 return 0; 13 }
2. 设置输出数据的宽度: cout.width()
1 #include <iostream> 2 using namespace std; 3 4 int main() 5 { 6 for (int i = 0; i < 100; i++) { 7 cout.width(3); // 仅对下一个cout输出生效 8 cout << i << endl; 9 } 10 }
3. 计算经过多少天之后是星期几
1 // base: 当前是星期几 2 // passed: 过了多少天 3 int week(int base, int passed) 4 { 5 int week = (base+passed) % 7; 6 int week_a[7] = {7,1,2,3,4,5,6}; 7 return week_a[week]; 8 }
4. Hello, World!的大小(sizeof)
1 #include <iostream> 2 using namespace std; 3 4 int main(void) 5 { 6 int n; 7 string hello = "Hello, World!"; 8 9 n = sizeof(hello); 10 cout << n << endl; 11 return 0; 12 }
5. 创建素数表的函数
1 #include <iostream> 2 #include <vector> 3 using namespace std; 4 5 int creat_prime(int n, int prime[]) 6 { 7 prime[0] = 0; 8 prime[1] = 0; 9 // 素数标志 10 for (int i=2; i<n; i++) { 11 prime[i] = 1; 12 } 13 // 遍历到根号n 14 for (int i=2; (i*i)<n; i++) { 15 if (prime[i] == 1) { 16 for (int j=2*i; j<=n; j++) { 17 if ((j%i) == 0) { 18 prime[j] = 0; 19 } 20 } 21 } 22 } 23 return 0; 24 } 25 26 int main(void) 27 { 28 int n; 29 cin >> n; 30 // 31 int *prime = new int[n]; 32 creat_prime(n, prime); 33 for (int i=0; i<n; i++) { 34 if (prime[i] != 0) { 35 cout << i << endl; 36 } 37 } 38 return 0; 39 }
6. 辗转法求最大公约数
1 #include <iostream> 2 #include <vector> 3 using namespace std; 4 5 int gcd(int m, int n) 6 { 7 int r = m % n; 8 if (r == 0) { 9 return n; 10 } 11 else { 12 return gcd(n, r); 13 } 14 } 15 16 int main() 17 { 18 int a, b; 19 cin >> a >> b; 20 cout << gcd(a, b); 21 }
博客园:http://www.cnblogs.com/linux-farmer/