1、撕页问题:撕去一页,剩余页码和16023,问原书总共多少页,撕去的是第几页。
#include<iostream> using std::cout; using std::endl; int main() { int recent_page; int total_pages = 0; const int REST_PAGES = 16023; int posible_page = -1; // 枚举页数 int k = -1; for (recent_page = 1; k != 0; ++recent_page) { total_pages += recent_page; if (total_pages - REST_PAGES > 0) { k = (total_pages - REST_PAGES - 1) % 2; posible_page = (total_pages - REST_PAGES - 1) / 2; } } cout << "Total page is " << recent_page - 1 << endl; cout << "Posible page is " << posible_page << endl; return 0; }
2、计算标准差。
#include<iostream> using std::cin; using std::cout; using std::endl; #include<cmath> int main() { int n; // 浮点数个数 cin >> n; const int MAXLINE = 1000; double x[MAXLINE]; double sum = 0; for (int i = 0; i != n; ++i) { cin >> x[i]; sum += x[i]; } // 计算平均值 double ave = sum / n; // 计算标准差 sum = 0; for (int i = 0; i != n; ++i) { sum += (x[i] - ave) * (x[i] - ave); } double vari = sum / n; double std = sqrt(vari); cout << "Standard Deviation is " << std << endl; return 0; }
3、题目:函数process()用于分解字符串mainstr中的各单词并存入结构体数组。
#include<iostream> using std::cout; using std::cin; using std::endl; #include<cstring> struct WORDS { char w[30]; short w_len; } word[100]; int process(char *mainstr, struct WORDS *p); int main() { char str[] = " Hello world"; int words = process(str , word); cout << "words : " << words << endl; for (int i = 0; i != words; ++i) { cout << word[i].w << endl; } return 0; } int process(char *mainstr, struct WORDS *p) { int str_index = 0; int word_index = 0; int words = 0; // 跳过开头空格 while (isspace(*(mainstr + str_index))) { ++str_index; } // 处理单词 while (str_index < strlen(mainstr) - 1) { while (!isspace(*(mainstr + str_index))) { (p + words)->w[word_index++] = *(mainstr + str_index); ++str_index; } ++str_index; // 跳过空格 // 准备记录下一个单词 (p + words) -> w[word_index] = ‘\0‘; ++words; word_index = 0; } return words; }
while (str_index < strlen(mainstr) - 1) 因为这里没有写 -1 调试了近一个小时。。。下次再遇到边界条件一定要先写测试,确认无误再往下写
4、重载abs。
#include<iostream> using std::cout; using std::endl; // 版本1 int abs(int x) { cout << "Use int abs(int x):" << endl; if (x > 0) { return x; } return -x; } // 版本2 double abs(double x) { cout << "Use double abs(double x):" << endl; if (x > 0) { return x; } return -x; } // 函数测试 int main() { cout << abs(-1.7) << endl; cout << abs(-1) << endl; return 0; }
原文:http://www.cnblogs.com/xkxf/p/6441298.html