第25章-C++初级实战案例(20个)
案例1:温度转换器
案例描述
实现摄氏度与华氏度之间的相互转换。
知识点
- 基本输入输出
- 数学运算
- 函数封装
完整代码
#include<iostream>#include<iomanip>usingnamespace std;// 摄氏度转华氏度doublecelsiusToFahrenheit(double celsius){return celsius *9.0/5.0+32.0;}// 华氏度转摄氏度doublefahrenheitToCelsius(double fahrenheit){return(fahrenheit -32.0)*5.0/9.0;}intmain(){int choice;double temp, result; cout <<"========== 温度转换器 =========="<< endl; cout <<"1. 摄氏度转华氏度"<< endl; cout <<"2. 华氏度转摄氏度"<< endl; cout <<"请选择(1/2): "; cin >> choice;if(choice ==1){ cout <<"请输入摄氏度: "; cin >> temp; result =celsiusToFahrenheit(temp); cout << fixed <<setprecision(2); cout << temp <<"°C = "<< result <<"°F"<< endl;}elseif(choice ==2){ cout <<"请输入华氏度: "; cin >> temp; result =fahrenheitToCelsius(temp); cout << fixed <<setprecision(2); cout << temp <<"°F = "<< result <<"°C"<< endl;}else{ cout <<"无效选择!"<< endl;}return0;}运行示例
========== 温度转换器 ========== 1. 摄氏度转华氏度 2. 华氏度转摄氏度 请选择(1/2): 1 请输入摄氏度: 25 25.00°C = 77.00°F 案例2:判断闰年
案例描述
输入一个年份,判断是否为闰年。
知识点
- 条件判断
- 逻辑运算符
- 布尔类型
完整代码
#include<iostream>usingnamespace std;boolisLeapYear(int year){// 闰年条件:能被4整除但不能被100整除,或能被400整除return(year %4==0&& year %100!=0)||(year %400==0);}intmain(){int year; cout <<"请输入年份: "; cin >> year;if(isLeapYear(year)){ cout << year <<"年是闰年"<< endl;}else{ cout << year <<"年不是闰年"<< endl;}// 扩展:判断多个年份 cout <<"\n近10年的闰年有:"<< endl;for(int i = year; i < year +10; i++){if(isLeapYear(i)){ cout << i <<" ";}} cout << endl;return0;}运行示例
请输入年份: 2024 2024年是闰年 近10年的闰年有: 2024 2028 2032 案例3:计算阶乘
案例描述
计算给定数字的阶乘(n!)。
知识点
- 循环结构
- 递归函数
- 大数处理
完整代码
#include<iostream>usingnamespace std;// 方法1:循环实现longlongfactorialLoop(int n){if(n <0)return-1;// 错误标识if(n ==0|| n ==1)return1;longlong result =1;for(int i =2; i <= n; i++){ result *= i;}return result;}// 方法2:递归实现longlongfactorialRecursive(int n){if(n <0)return-1;if(n ==0|| n ==1)return1;return n *factorialRecursive(n -1);}intmain(){int num; cout <<"请输入一个非负整数: "; cin >> num;if(num <0){ cout <<"错误:阶乘不支持负数!"<< endl;return1;}if(num >20){ cout <<"警告:数字过大可能溢出,建议输入0-20之间的数"<< endl;}longlong result1 =factorialLoop(num);longlong result2 =factorialRecursive(num); cout << num <<"! = "<< result1 <<" (循环方法)"<< endl; cout << num <<"! = "<< result2 <<" (递归方法)"<< endl;// 显示阶乘表 cout <<"\n阶乘表 (0-10):"<< endl;for(int i =0; i <=10; i++){ cout << i <<"! = "<<factorialLoop(i)<< endl;}return0;}运行示例
请输入一个非负整数: 5 5! = 120 (循环方法) 5! = 120 (递归方法) 阶乘表 (0-10): 0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 362880 10! = 3628800 案例4:素数判断与生成
案例描述
判断一个数是否为素数,并生成指定范围内的所有素数。
知识点
- 算法优化
- 循环嵌套
- 数学逻辑
完整代码
#include<iostream>#include<cmath>#include<vector>usingnamespace std;// 判断是否为素数(优化版)boolisPrime(int n){if(n <=1)returnfalse;if(n <=3)returntrue;if(n %2==0|| n %3==0)returnfalse;// 只需检查到sqrt(n)for(int i =5; i * i <= n; i +=6){if(n % i ==0|| n %(i +2)==0){returnfalse;}}returntrue;}// 生成指定范围内的素数 vector<int>generatePrimes(int start,int end){ vector<int> primes;for(int i = start; i <= end; i++){if(isPrime(i)){ primes.push_back(i);}}return primes;}intmain(){int choice; cout <<"========== 素数工具 =========="<< endl; cout <<"1. 判断单个数是否为素数"<< endl; cout <<"2. 生成范围内的素数"<< endl; cout <<"请选择: "; cin >> choice;if(choice ==1){int num; cout <<"请输入一个数: "; cin >> num;if(isPrime(num)){ cout << num <<" 是素数"<< endl;}else{ cout << num <<" 不是素数"<< endl;}}elseif(choice ==2){int start, end; cout <<"请输入范围(起始 结束): "; cin >> start >> end; vector<int> primes =generatePrimes(start, end); cout << start <<" 到 "<< end <<" 之间的素数有 "<< primes.size()<<" 个:"<< endl;int count =0;for(int prime : primes){ cout << prime <<" "; count++;if(count %10==0) cout << endl;// 每行显示10个} cout << endl;}return0;}运行示例
========== 素数工具 ========== 1. 判断单个数是否为素数 2. 生成范围内的素数 请选择: 2 请输入范围(起始 结束): 1 50 1 到 50 之间的素数有 15 个: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 案例5:数组排序算法
案例描述
实现冒泡排序、选择排序和插入排序三种基本排序算法。
知识点
- 数组操作
- 排序算法
- 函数重载
完整代码
#include<iostream>#include<algorithm>usingnamespace std;// 打印数组voidprintArray(int arr[],int n){for(int i =0; i < n; i++){ cout << arr[i]<<" ";} cout << endl;}// 冒泡排序voidbubbleSort(int arr[],int n){for(int i =0; i < n -1; i++){bool swapped =false;for(int j =0; j < n - i -1; j++){if(arr[j]> arr[j +1]){swap(arr[j], arr[j +1]); swapped =true;}}// 如果没有发生交换,说明已经有序if(!swapped)break;}}// 选择排序voidselectionSort(int arr[],int n){for(int i =0; i < n -1; i++){int minIdx = i;for(int j = i +1; j < n; j++){if(arr[j]< arr[minIdx]){ minIdx = j;}}if(minIdx != i){swap(arr[i], arr[minIdx]);}}}// 插入排序voidinsertionSort(int arr[],int n){for(int i =1; i < n; i++){int key = arr[i];int j = i -1;// 将大于key的元素向后移动while(j >=0&& arr[j]> key){ arr[j +1]= arr[j]; j--;} arr[j +1]= key;}}intmain(){int arr[]={64,34,25,12,22,11,90};int n =sizeof(arr)/sizeof(arr[0]); cout <<"原始数组: ";printArray(arr, n);// 测试冒泡排序int arr1[]={64,34,25,12,22,11,90};bubbleSort(arr1, n); cout <<"冒泡排序: ";printArray(arr1, n);// 测试选择排序int arr2[]={64,34,25,12,22,11,90};selectionSort(arr2, n); cout <<"选择排序: ";printArray(arr2, n);// 测试插入排序int arr3[]={64,34,25,12,22,11,90};insertionSort(arr3, n); cout <<"插入排序: ";printArray(arr3, n);return0;}运行示例
原始数组: 64 34 25 12 22 11 90 冒泡排序: 11 12 22 25 34 64 90 选择排序: 11 12 22 25 34 64 90 插入排序: 11 12 22 25 34 64 90 案例6:字符串反转
案例描述
实现字符串反转的多种方法。
知识点
- 字符串操作
- 双指针技巧
- STL算法
完整代码
#include<iostream>#include<string>#include<algorithm>usingnamespace std;// 方法1:使用双指针voidreverseString1(string& str){int left =0;int right = str.length()-1;while(left < right){swap(str[left], str[right]); left++; right--;}}// 方法2:使用STL的reverse函数voidreverseString2(string& str){reverse(str.begin(), str.end());}// 方法3:递归方法voidreverseString3(string& str,int left,int right){if(left >= right)return;swap(str[left], str[right]);reverseString3(str, left +1, right -1);}// 反转单词顺序(保持单词内部字符顺序) string reverseWords(const string& str){ string result =""; string word ="";for(int i = str.length()-1; i >=0; i--){if(str[i]==' '){if(!word.empty()){reverse(word.begin(), word.end()); result += word +" "; word ="";}}else{ word += str[i];}}if(!word.empty()){reverse(word.begin(), word.end()); result += word;}return result;}intmain(){ string str1 ="Hello World"; string str2 ="Hello World"; string str3 ="Hello World"; string str4 ="Hello World from C++"; cout <<"原始字符串: "<< str1 << endl;reverseString1(str1); cout <<"方法1(双指针): "<< str1 << endl;reverseString2(str2); cout <<"方法2(STL): "<< str2 << endl;reverseString3(str3,0, str3.length()-1); cout <<"方法3(递归): "<< str3 << endl; cout <<"\n原始句子: "<< str4 << endl; cout <<"反转单词顺序: "<<reverseWords(str4)<< endl;return0;}运行示例
原始字符串: Hello World 方法1(双指针): dlroW olleH 方法2(STL): dlroW olleH 方法3(递归): dlroW olleH 原始句子: Hello World from C++ 反转单词顺序: C++ from World Hello 案例7:查找数组中的最大值和最小值
案例描述
在数组中查找最大值、最小值及其位置。
知识点
- 数组遍历
- 变量更新
- 位置记录
完整代码
#include<iostream>#include<climits>usingnamespace std;structMinMax{int minValue;int maxValue;int minIndex;int maxIndex;}; MinMax findMinMax(int arr[],int n){ MinMax result; result.minValue = INT_MAX; result.maxValue = INT_MIN; result.minIndex =-1; result.maxIndex =-1;for(int i =0; i < n; i++){if(arr[i]< result.minValue){ result.minValue = arr[i]; result.minIndex = i;}if(arr[i]> result.maxValue){ result.maxValue = arr[i]; result.maxIndex = i;}}return result;}// 查找第二大的数intfindSecondMax(int arr[],int n){if(n <2)return-1;int max1 = INT_MIN, max2 = INT_MIN;for(int i =0; i < n; i++){if(arr[i]> max1){ max2 = max1; max1 = arr[i];}elseif(arr[i]> max2 && arr[i]< max1){ max2 = arr[i];}}return(max2 == INT_MIN)?-1: max2;}intmain(){int arr[]={45,23,67,12,89,34,78,56};int n =sizeof(arr)/sizeof(arr[0]); cout <<"数组元素: ";for(int i =0; i < n; i++){ cout << arr[i]<<" ";} cout << endl; MinMax result =findMinMax(arr, n); cout <<"\n最小值: "<< result.minValue <<" (位置: "<< result.minIndex <<")"<< endl; cout <<"最大值: "<< result.maxValue <<" (位置: "<< result.maxIndex <<")"<< endl;int secondMax =findSecondMax(arr, n);if(secondMax !=-1){ cout <<"第二大的数: "<< secondMax << endl;} cout <<"数值范围: "<< result.maxValue - result.minValue << endl;return0;}运行示例
数组元素: 45 23 67 12 89 34 78 56 最小值: 12 (位置: 3) 最大值: 89 (位置: 4) 第二大的数: 78 数值范围: 77 案例8:斐波那契数列
案例描述
生成斐波那契数列的前n项。
知识点
- 递归与迭代
- 动态规划思想
- 性能优化
完整代码
#include<iostream>#include<vector>usingnamespace std;// 方法1:递归(效率低)longlongfibRecursive(int n){if(n <=1)return n;returnfibRecursive(n -1)+fibRecursive(n -2);}// 方法2:迭代(效率高)longlongfibIterative(int n){if(n <=1)return n;longlong a =0, b =1;for(int i =2; i <= n; i++){longlong temp = a + b; a = b; b = temp;}return b;}// 方法3:使用数组存储(动态规划) vector<longlong>fibArray(int n){ vector<longlong>fib(n +1); fib[0]=0;if(n >0) fib[1]=1;for(int i =2; i <= n; i++){ fib[i]= fib[i -1]+ fib[i -2];}return fib;}intmain(){int n; cout <<"请输入要生成的斐波那契数列项数: "; cin >> n;if(n <0){ cout <<"错误:请输入非负整数!"<< endl;return1;}if(n >50){ cout <<"警告:数字过大可能溢出,建议输入0-50之间的数"<< endl;}// 使用迭代方法生成数列 cout <<"\n斐波那契数列前 "<< n +1<<" 项:"<< endl;for(int i =0; i <= n; i++){ cout <<"F("<< i <<") = "<<fibIterative(i)<< endl;}// 使用数组方法一次性生成 cout <<"\n使用数组方法:"<< endl; vector<longlong> fibSeq =fibArray(n);for(int i =0; i <= n; i++){ cout << fibSeq[i]<<" ";if((i +1)%10==0) cout << endl;} cout << endl;return0;}运行示例
请输入要生成的斐波那契数列项数: 10 斐波那契数列前 11 项: F(0) = 0 F(1) = 1 F(2) = 1 F(3) = 2 F(4) = 3 F(5) = 5 F(6) = 8 F(7) = 13 F(8) = 21 F(9) = 34 F(10) = 55 使用数组方法: 0 1 1 2 3 5 8 13 21 34 55 案例9:回文字符串判断
案例描述
判断一个字符串是否为回文(正读和反读都一样)。
知识点
- 字符串比较
- 双指针技巧
- 字符处理
完整代码
#include<iostream>#include<string>#include<cctype>usingnamespace std;// 方法1:基本判断boolisPalindrome1(const string& str){int left =0;int right = str.length()-1;while(left < right){if(str[left]!= str[right]){returnfalse;} left++; right--;}returntrue;}// 方法2:忽略大小写和非字母数字字符boolisPalindrome2(const string& str){int left =0;int right = str.length()-1;while(left < right){// 跳过非字母数字字符while(left < right &&!isalnum(str[left])) left++;while(left < right &&!isalnum(str[right])) right--;// 比较(忽略大小写)if(tolower(str[left])!=tolower(str[right])){returnfalse;} left++; right--;}returntrue;}// 找出最长回文子串 string longestPalindrome(const string& str){int n = str.length();if(n ==0)return"";int maxLen =1;int start =0;// 检查所有子串for(int i =0; i < n; i++){for(int j = i; j < n; j++){bool isPalin =true;int left = i, right = j;while(left < right){if(str[left]!= str[right]){ isPalin =false;break;} left++; right--;}if(isPalin &&(j - i +1)> maxLen){ maxLen = j - i +1; start = i;}}}return str.substr(start, maxLen);}intmain(){ string test1 ="racecar"; string test2 ="hello"; string test3 ="A man, a plan, a canal: Panama"; string test4 ="abcbabcba"; cout <<"\""<< test1 <<"\" 是回文: "<<(isPalindrome1(test1)?"是":"否")<< endl; cout <<"\""<< test2 <<"\" 是回文: "<<(isPalindrome1(test2)?"是":"否")<< endl; cout <<"\""<< test3 <<"\" 是回文(忽略符号和大小写): "<<(isPalindrome2(test3)?"是":"否")<< endl; cout <<"\n\""<< test4 <<"\" 的最长回文子串: \""<<longestPalindrome(test4)<<"\""<< endl;// 交互式测试 cout <<"\n请输入一个字符串: "; string userInput;getline(cin, userInput); cout <<"基本判断: "<<(isPalindrome1(userInput)?"是回文":"不是回文")<< endl; cout <<"高级判断: "<<(isPalindrome2(userInput)?"是回文":"不是回文")<< endl;return0;}运行示例
"racecar" 是回文: 是 "hello" 是回文: 否 "A man, a plan, a canal: Panama" 是回文(忽略符号和大小写): 是 "abcbabcba" 的最长回文子串: "abcbabcba" 请输入一个字符串: level 基本判断: 是回文 高级判断: 是回文 案例10:简易计算器
案例描述
实现一个支持加减乘除和括号的简易计算器。
知识点
- 表达式解析
- 运算符优先级
- 栈的应用
完整代码
#include<iostream>#include<string>#include<stack>#include<cctype>usingnamespace std;// 基础四则运算计算器classSimpleCalculator{private:// 判断运算符优先级intprecedence(char op){if(op =='+'|| op =='-')return1;if(op =='*'|| op =='/')return2;return0;}// 执行运算doubleapplyOp(double a,double b,char op){switch(op){case'+':return a + b;case'-':return a - b;case'*':return a * b;case'/':if(b ==0){throwruntime_error("除数不能为0");}return a / b;}return0;}public:// 计算表达式doubleevaluate(string expression){ stack<double> values;// 存储数字 stack<char> operators;// 存储运算符for(int i =0; i < expression.length(); i++){// 跳过空格if(isspace(expression[i]))continue;// 如果是数字if(isdigit(expression[i])|| expression[i]=='.'){double val =0;bool isDecimal =false;double decimalPlace =0.1;while(i < expression.length()&&(isdigit(expression[i])|| expression[i]=='.')){if(expression[i]=='.'){ isDecimal =true;}elseif(!isDecimal){ val = val *10+(expression[i]-'0');}else{ val +=(expression[i]-'0')* decimalPlace; decimalPlace *=0.1;} i++;} i--; values.push(val);}// 如果是左括号elseif(expression[i]=='('){ operators.push(expression[i]);}// 如果是右括号elseif(expression[i]==')'){while(!operators.empty()&& operators.top()!='('){double val2 = values.top(); values.pop();double val1 = values.top(); values.pop();char op = operators.top(); operators.pop(); values.push(applyOp(val1, val2, op));}if(!operators.empty()) operators.pop();// 移除'('}// 如果是运算符elseif(expression[i]=='+'|| expression[i]=='-'|| expression[i]=='*'|| expression[i]=='/'){while(!operators.empty()&&precedence(operators.top())>=precedence(expression[i])){double val2 = values.top(); values.pop();double val1 = values.top(); values.pop();char op = operators.top(); operators.pop(); values.push(applyOp(val1, val2, op));} operators.push(expression[i]);}}// 处理剩余的运算while(!operators.empty()){double val2 = values.top(); values.pop();double val1 = values.top(); values.pop();char op = operators.top(); operators.pop(); values.push(applyOp(val1, val2, op));}return values.top();}};intmain(){ SimpleCalculator calc; string expression; cout <<"========== 简易计算器 =========="<< endl; cout <<"支持 +、-、*、/、() 运算"<< endl; cout <<"输入 'quit' 退出"<< endl; cout <<"==============================="<< endl;while(true){ cout <<"\n请输入表达式: ";getline(cin, expression);if(expression =="quit"|| expression =="exit"){ cout <<"再见!"<< endl;break;}try{double result = calc.evaluate(expression); cout <<"结果 = "<< result << endl;}catch(const exception& e){ cout <<"错误: "<< e.what()<< endl;}}return0;}运行示例
========== 简易计算器 ========== 支持 +、-、*、/、() 运算 输入 'quit' 退出 =============================== 请输入表达式: 2 + 3 * 4 结果 = 14 请输入表达式: (2 + 3) * 4 结果 = 20 请输入表达式: 10 / 2 + 3 结果 = 8 请输入表达式: quit 再见! 案例11:猜数字游戏
案例描述
实现一个经典的猜数字游戏,系统随机生成一个数字,玩家猜测并获得提示。
知识点
- 随机数生成
- 循环控制
- 用户交互
完整代码
#include<iostream>#include<cstdlib>#include<ctime>usingnamespace std;classGuessGame{private:int targetNumber;int attempts;int maxAttempts;int minRange;int maxRange;public:GuessGame(int min =1,int max =100,int maxTries =10):minRange(min),maxRange(max),maxAttempts(maxTries),attempts(0){srand(time(0)); targetNumber =rand()%(maxRange - minRange +1)+ minRange;}voidplay(){ cout <<"\n========== 猜数字游戏 =========="<< endl; cout <<"我想了一个 "<< minRange <<" 到 "<< maxRange <<" 之间的数字"<< endl; cout <<"你有 "<< maxAttempts <<" 次机会来猜"<< endl; cout <<"==============================="<< endl;while(attempts < maxAttempts){ cout <<"\n第 "<<(attempts +1)<<" 次猜测,请输入: ";int guess; cin >> guess;if(guess < minRange || guess > maxRange){ cout <<"请输入 "<< minRange <<" 到 "<< maxRange <<" 之间的数字!"<< endl;continue;} attempts++;if(guess == targetNumber){ cout <<"恭喜你!猜对了!"<< endl; cout <<"你用了 "<< attempts <<" 次猜中了数字 "<< targetNumber << endl;return;}elseif(guess < targetNumber){ cout <<"太小了!";if(targetNumber - guess >10){ cout <<"(还差得远呢)";}else{ cout <<"(快接近了)";} cout << endl;}else{ cout <<"太大了!";if(guess - targetNumber >10){ cout <<"(还差得远呢)";}else{ cout <<"(快接近了)";} cout << endl;} cout <<"剩余机会: "<<(maxAttempts - attempts)<< endl;} cout <<"\n游戏结束!正确答案是: "<< targetNumber << endl;}};intmain(){char playAgain;do{int difficulty; cout <<"选择难度:1.简单(1-50,15次) 2.中等(1-100,10次) 3.困难(1-200,8次): "; cin >> difficulty; GuessGame* game;switch(difficulty){case1: game =newGuessGame(1,50,15);break;case3: game =newGuessGame(1,200,8);break;default: game =newGuessGame(1,100,10);} game->play();delete game; cout <<"\n再玩一次?(y/n): "; cin >> playAgain;}while(playAgain =='y'|| playAgain =='Y'); cout <<"谢谢游玩!"<< endl;return0;}运行示例
选择难度:1.简单(1-50,15次) 2.中等(1-100,10次) 3.困难(1-200,8次): 2 ========== 猜数字游戏 ========== 我想了一个 1 到 100 之间的数字 你有 10 次机会来猜 =============================== 第 1 次猜测,请输入: 50 太小了!(还差得远呢) 剩余机会: 9 第 2 次猜测,请输入: 75 太大了!(快接近了) 剩余机会: 8 第 3 次猜测,请输入: 68 恭喜你!猜对了! 你用了 3 次猜中了数字 68 再玩一次?(y/n): n 谢谢游玩! 案例12:二维数组矩阵操作
案例描述
实现矩阵的基本操作:转置、加法、乘法。
知识点
- 二维数组
- 矩阵运算
- 函数传递二维数组
完整代码
#include<iostream>#include<iomanip>usingnamespace std;constint MAX_SIZE =10;// 打印矩阵voidprintMatrix(int mat[][MAX_SIZE],int rows,int cols){for(int i =0; i < rows; i++){for(int j =0; j < cols; j++){ cout <<setw(4)<< mat[i][j]<<" ";} cout << endl;}}// 矩阵转置voidtranspose(int mat[][MAX_SIZE],int result[][MAX_SIZE],int rows,int cols){for(int i =0; i < rows; i++){for(int j =0; j < cols; j++){ result[j][i]= mat[i][j];}}}// 矩阵加法booladdMatrix(int mat1[][MAX_SIZE],int mat2[][MAX_SIZE],int result[][MAX_SIZE],int rows,int cols){for(int i =0; i < rows; i++){for(int j =0; j < cols; j++){ result[i][j]= mat1[i][j]+ mat2[i][j];}}returntrue;}// 矩阵乘法boolmultiplyMatrix(int mat1[][MAX_SIZE],int mat2[][MAX_SIZE],int result[][MAX_SIZE],int r1,int c1,int r2,int c2){if(c1 != r2){returnfalse;// 矩阵不能相乘}// 初始化结果矩阵for(int i =0; i < r1; i++){for(int j =0; j < c2; j++){ result[i][j]=0;}}// 计算乘积for(int i =0; i < r1; i++){for(int j =0; j < c2; j++){for(int k =0; k < c1; k++){ result[i][j]+= mat1[i][k]* mat2[k][j];}}}returntrue;}intmain(){int mat1[MAX_SIZE][MAX_SIZE]={{1,2,3},{4,5,6}};int mat2[MAX_SIZE][MAX_SIZE]={{7,8,9},{10,11,12}};int mat3[MAX_SIZE][MAX_SIZE]={{1,2},{3,4},{5,6}};int result[MAX_SIZE][MAX_SIZE]; cout <<"矩阵A (2x3):"<< endl;printMatrix(mat1,2,3); cout <<"\n矩阵B (2x3):"<< endl;printMatrix(mat2,2,3); cout <<"\n矩阵C (3x2):"<< endl;printMatrix(mat3,3,2);// 转置 cout <<"\n矩阵A的转置:"<< endl;transpose(mat1, result,2,3);printMatrix(result,3,2);// 加法 cout <<"\n矩阵A + 矩阵B:"<< endl;addMatrix(mat1, mat2, result,2,3);printMatrix(result,2,3);// 乘法 cout <<"\n矩阵A × 矩阵C:"<< endl;if(multiplyMatrix(mat1, mat3, result,2,3,3,2)){printMatrix(result,2,2);}else{ cout <<"矩阵维度不匹配,无法相乘!"<< endl;}return0;}运行示例
矩阵A (2x3): 1 2 3 4 5 6 矩阵B (2x3): 7 8 9 10 11 12 矩阵C (3x2): 1 2 3 4 5 6 矩阵A的转置: 1 4 2 5 3 6 矩阵A + 矩阵B: 8 10 12 14 16 18 矩阵A × 矩阵C: 22 28 49 64 案例13:成绩统计系统
案例描述
统计一组学生成绩的平均分、最高分、最低分、及格率等。
知识点
- 数组统计
- 数据分析
- 格式化输出
完整代码
#include<iostream>#include<iomanip>#include<algorithm>usingnamespace std;structScoreStats{double average;double highest;double lowest;double passRate;double excellentRate;int passCount;int excellentCount;}; ScoreStats analyzeScores(double scores[],int n){ ScoreStats stats;double sum =0; stats.highest = scores[0]; stats.lowest = scores[0]; stats.passCount =0; stats.excellentCount =0;for(int i =0; i < n; i++){ sum += scores[i];if(scores[i]> stats.highest) stats.highest = scores[i];if(scores[i]< stats.lowest) stats.lowest = scores[i];if(scores[i]>=60) stats.passCount++;if(scores[i]>=90) stats.excellentCount++;} stats.average = sum / n; stats.passRate =(stats.passCount *100.0)/ n; stats.excellentRate =(stats.excellentCount *100.0)/ n;return stats;}voidprintGradeDistribution(double scores[],int n){int distribution[5]={0};// 不及格、及格、中等、良好、优秀for(int i =0; i < n; i++){if(scores[i]<60) distribution[0]++;elseif(scores[i]<70) distribution[1]++;elseif(scores[i]<80) distribution[2]++;elseif(scores[i]<90) distribution[3]++;else distribution[4]++;} cout <<"\n成绩分布:"<< endl; cout <<"不及格(<60): "<< distribution[0]<<" 人 ("<< fixed <<setprecision(1)<<(distribution[0]*100.0/ n)<<"%)"<< endl; cout <<"及格(60-69): "<< distribution[1]<<" 人 ("<<(distribution[1]*100.0/ n)<<"%)"<< endl; cout <<"中等(70-79): "<< distribution[2]<<" 人 ("<<(distribution[2]*100.0/ n)<<"%)"<< endl; cout <<"良好(80-89): "<< distribution[3]<<" 人 ("<<(distribution[3]*100.0/ n)<<"%)"<< endl; cout <<"优秀(90-100): "<< distribution[4]<<" 人 ("<<(distribution[4]*100.0/ n)<<"%)"<< endl;}intmain(){constint MAX_STUDENTS =100;double scores[MAX_STUDENTS];int n; cout <<"请输入学生人数: "; cin >> n;if(n <=0|| n > MAX_STUDENTS){ cout <<"学生人数无效!"<< endl;return1;} cout <<"请输入 "<< n <<" 个学生的成绩:"<< endl;for(int i =0; i < n; i++){ cout <<"学生"<<(i +1)<<": "; cin >> scores[i];if(scores[i]<0|| scores[i]>100){ cout <<"成绩无效,请重新输入!"<< endl; i--;}} ScoreStats stats =analyzeScores(scores, n); cout <<"\n========== 成绩统计结果 =========="<< endl; cout << fixed <<setprecision(2); cout <<"平均分: "<< stats.average << endl; cout <<"最高分: "<< stats.highest << endl; cout <<"最低分: "<< stats.lowest << endl; cout <<"及格人数: "<< stats.passCount <<" 人"<< endl; cout <<"及格率: "<< stats.passRate <<"%"<< endl; cout <<"优秀人数: "<< stats.excellentCount <<" 人"<< endl; cout <<"优秀率: "<< stats.excellentRate <<"%"<< endl;printGradeDistribution(scores, n);// 排序后显示sort(scores, scores + n); cout <<"\n成绩排序(从低到高):"<< endl;for(int i =0; i < n; i++){ cout << scores[i]<<" ";if((i +1)%10==0) cout << endl;} cout << endl;return0;}运行示例
请输入学生人数: 10 请输入 10 个学生的成绩: 学生1: 85 学生2: 92 学生3: 78 学生4: 65 学生5: 88 学生6: 76 学生7: 95 学生8: 58 学生9: 82 学生10: 90 ========== 成绩统计结果 ========== 平均分: 80.90 最高分: 95.00 最低分: 58.00 及格人数: 9 人 及格率: 90.00% 优秀人数: 3 人 优秀率: 30.00% 成绩分布: 不及格(<60): 1 人 (10.0%) 及格(60-69): 1 人 (10.0%) 中等(70-79): 2 人 (20.0%) 良好(80-89): 3 人 (30.0%) 优秀(90-100): 3 人 (30.0%) 成绩排序(从低到高): 58.00 65.00 76.00 78.00 82.00 85.00 88.00 90.00 92.00 95.00 案例14:字符串统计分析
案例描述
统计字符串中字母、数字、空格和其他字符的数量。
知识点
- 字符分类函数
- 字符串遍历
- 统计分析
完整代码
#include<iostream>#include<string>#include<cctype>usingnamespace std;structCharStats{int letters;int digits;int spaces;int uppercase;int lowercase;int punctuation;int others;int total;}; CharStats analyzeString(const string& str){ CharStats stats ={0,0,0,0,0,0,0,0};for(char ch : str){ stats.total++;if(isalpha(ch)){ stats.letters++;if(isupper(ch)) stats.uppercase++;else stats.lowercase++;}elseif(isdigit(ch)){ stats.digits++;}elseif(isspace(ch)){ stats.spaces++;}elseif(ispunct(ch)){ stats.punctuation++;}else{ stats.others++;}}return stats;}// 统计单词数量intcountWords(const string& str){int count =0;bool inWord =false;for(char ch : str){if(isspace(ch)){ inWord =false;}elseif(!inWord){ inWord =true; count++;}}return count;}// 查找最长单词 string findLongestWord(const string& str){ string longestWord =""; string currentWord ="";for(char ch : str){if(isalnum(ch)){ currentWord += ch;}else{if(currentWord.length()> longestWord.length()){ longestWord = currentWord;} currentWord ="";}}// 检查最后一个单词if(currentWord.length()> longestWord.length()){ longestWord = currentWord;}return longestWord;}intmain(){ string text; cout <<"请输入一段文本: "<< endl;getline(cin, text); CharStats stats =analyzeString(text); cout <<"\n========== 字符统计分析 =========="<< endl; cout <<"总字符数: "<< stats.total << endl; cout <<"字母数: "<< stats.letters <<" (大写:"<< stats.uppercase <<", 小写:"<< stats.lowercase <<")"<< endl; cout <<"数字数: "<< stats.digits << endl; cout <<"空格数: "<< stats.spaces << endl; cout <<"标点符号: "<< stats.punctuation << endl; cout <<"其他字符: "<< stats.others << endl;int wordCount =countWords(text); string longestWord =findLongestWord(text); cout <<"\n单词数: "<< wordCount << endl; cout <<"最长单词: \""<< longestWord <<"\" (长度: "<< longestWord.length()<<")"<< endl;// 字符频率统计 cout <<"\n字母频率统计:"<< endl;int freq[26]={0};for(char ch : text){if(isalpha(ch)){ freq[tolower(ch)-'a']++;}}for(int i =0; i <26; i++){if(freq[i]>0){ cout <<char('a'+ i)<<": "<< freq[i]<<" ";if((i +1)%5==0) cout << endl;}} cout << endl;return0;}运行示例
请输入一段文本: Hello World! This is a C++ programming example. Count123 ========== 字符统计分析 ========== 总字符数: 56 字母数: 43 (大写:5, 小写:38) 数字数: 3 空格数: 7 标点符号: 2 其他字符: 1 单词数: 8 最长单词: "programming" (长度: 11) 字母频率统计: a: 3 c: 2 d: 1 e: 4 g: 2 h: 2 i: 3 l: 3 m: 3 n: 2 o: 4 p: 2 r: 3 s: 2 t: 2 u: 1 w: 1 x: 1 案例15:简易银行账户系统
案例描述
实现一个简单的银行账户管理系统,支持存款、取款、查询余额等操作。
知识点
- 结构体应用
- 函数封装
- 数据验证
完整代码
#include<iostream>#include<string>#include<iomanip>usingnamespace std;structBankAccount{ string accountNumber; string ownerName;double balance; string password;};classSimpleBankSystem{private: BankAccount accounts[100];int accountCount;intfindAccount(const string& accountNumber){for(int i =0; i < accountCount; i++){if(accounts[i].accountNumber == accountNumber){return i;}}return-1;}public:SimpleBankSystem():accountCount(0){}voidcreateAccount(){if(accountCount >=100){ cout <<"系统已满,无法创建新账户!"<< endl;return;} BankAccount newAccount; cout <<"\n创建新账户"<< endl; cout <<"账号: "; cin >> newAccount.accountNumber;if(findAccount(newAccount.accountNumber)!=-1){ cout <<"账号已存在!"<< endl;return;} cout <<"户名: "; cin.ignore();getline(cin, newAccount.ownerName); cout <<"初始存款: "; cin >> newAccount.balance;if(newAccount.balance <0){ cout <<"初始存款不能为负!"<< endl;return;} cout <<"设置密码: "; cin >> newAccount.password; accounts[accountCount++]= newAccount; cout <<"账户创建成功!"<< endl;}voiddeposit(){ string accountNumber;double amount; cout <<"\n存款"<< endl; cout <<"账号: "; cin >> accountNumber;int index =findAccount(accountNumber);if(index ==-1){ cout <<"账号不存在!"<< endl;return;} cout <<"存款金额: "; cin >> amount;if(amount <=0){ cout <<"存款金额必须大于0!"<< endl;return;} accounts[index].balance += amount; cout <<"存款成功!当前余额: "<< fixed <<setprecision(2)<< accounts[index].balance <<" 元"<< endl;}voidwithdraw(){ string accountNumber, password;double amount; cout <<"\n取款"<< endl; cout <<"账号: "; cin >> accountNumber;int index =findAccount(accountNumber);if(index ==-1){ cout <<"账号不存在!"<< endl;return;} cout <<"密码: "; cin >> password;if(password != accounts[index].password){ cout <<"密码错误!"<< endl;return;} cout <<"取款金额: "; cin >> amount;if(amount <=0){ cout <<"取款金额必须大于0!"<< endl;return;}if(amount > accounts[index].balance){ cout <<"余额不足!当前余额: "<< fixed <<setprecision(2)<< accounts[index].balance <<" 元"<< endl;return;} accounts[index].balance -= amount; cout <<"取款成功!当前余额: "<< fixed <<setprecision(2)<< accounts[index].balance <<" 元"<< endl;}voidcheckBalance(){ string accountNumber, password; cout <<"\n查询余额"<< endl; cout <<"账号: "; cin >> accountNumber;int index =findAccount(accountNumber);if(index ==-1){ cout <<"账号不存在!"<< endl;return;} cout <<"密码: "; cin >> password;if(password != accounts[index].password){ cout <<"密码错误!"<< endl;return;} cout <<"\n账户信息"<< endl; cout <<"账号: "<< accounts[index].accountNumber << endl; cout <<"户名: "<< accounts[index].ownerName << endl; cout <<"余额: "<< fixed <<setprecision(2)<< accounts[index].balance <<" 元"<< endl;}voidshowMenu(){ cout <<"\n========== 简易银行系统 =========="<< endl; cout <<"1. 创建账户"<< endl; cout <<"2. 存款"<< endl; cout <<"3. 取款"<< endl; cout <<"4. 查询余额"<< endl; cout <<"5. 退出"<< endl; cout <<"================================="<< endl; cout <<"请选择: ";}};intmain(){ SimpleBankSystem bank;int choice;while(true){ bank.showMenu(); cin >> choice;switch(choice){case1: bank.createAccount();break;case2: bank.deposit();break;case3: bank.withdraw();break;case4: bank.checkBalance();break;case5: cout <<"感谢使用!再见!"<< endl;return0;default: cout <<"无效选择!"<< endl;}}return0;}运行示例
========== 简易银行系统 ========== 1. 创建账户 2. 存款 3. 取款 4. 查询余额 5. 退出 ================================= 请选择: 1 创建新账户 账号: 1001 户名: 张三 初始存款: 1000 设置密码: 123456 账户创建成功! ========== 简易银行系统 ========== 请选择: 2 存款 账号: 1001 存款金额: 500 存款成功!当前余额: 1500.00 元 ========== 简易银行系统 ========== 请选择: 3 取款 账号: 1001 密码: 123456 取款金额: 200 取款成功!当前余额: 1300.00 元 案例16:进制转换器
案例描述
实现二进制、八进制、十进制、十六进制之间的相互转换。
知识点
- 进制转换算法
- 字符串处理
- 数学运算
完整代码
#include<iostream>#include<string>#include<algorithm>usingnamespace std;// 十进制转其他进制 string decimalToBase(int decimal,int base){if(decimal ==0)return"0"; string result ="";constchar digits[]="0123456789ABCDEF";bool isNegative = decimal <0; decimal =abs(decimal);while(decimal >0){ result += digits[decimal % base]; decimal /= base;}if(isNegative) result +='-';reverse(result.begin(), result.end());return result;}// 其他进制转十进制intbaseToDecimal(const string& number,int base){int result =0;int power =1;bool isNegative =(number[0]=='-');int startPos = isNegative ?1:0;for(int i = number.length()-1; i >= startPos; i--){char digit = number[i];int value;if(digit >='0'&& digit <='9'){ value = digit -'0';}elseif(digit >='A'&& digit <='F'){ value = digit -'A'+10;}elseif(digit >='a'&& digit <='f'){ value = digit -'a'+10;}else{return-1;// 无效字符}if(value >= base){return-1;// 数字超出进制范围} result += value * power; power *= base;}return isNegative ?-result : result;}voidshowConversions(int decimal){ cout <<"\n========== 进制转换结果 =========="<< endl; cout <<"十进制: "<< decimal << endl; cout <<"二进制: "<<decimalToBase(decimal,2)<< endl; cout <<"八进制: "<<decimalToBase(decimal,8)<< endl; cout <<"十六进制: "<<decimalToBase(decimal,16)<< endl; cout <<"================================"<< endl;}intmain(){int choice;while(true){ cout <<"\n========== 进制转换器 =========="<< endl; cout <<"1. 十进制转其他进制"<< endl; cout <<"2. 二进制转十进制"<< endl; cout <<"3. 八进制转十进制"<< endl; cout <<"4. 十六进制转十进制"<< endl; cout <<"5. 退出"<< endl; cout <<"==============================="<< endl; cout <<"请选择: "; cin >> choice;if(choice ==5){ cout <<"再见!"<< endl;break;}switch(choice){case1:{int decimal; cout <<"请输入十进制数: "; cin >> decimal;showConversions(decimal);break;}case2:{ string binary; cout <<"请输入二进制数: "; cin >> binary;int decimal =baseToDecimal(binary,2);if(decimal ==-1){ cout <<"无效的二进制数!"<< endl;}else{showConversions(decimal);}break;}case3:{ string octal; cout <<"请输入八进制数: "; cin >> octal;int decimal =baseToDecimal(octal,8);if(decimal ==-1){ cout <<"无效的八进制数!"<< endl;}else{showConversions(decimal);}break;}case4:{ string hex; cout <<"请输入十六进制数: "; cin >> hex;int decimal =baseToDecimal(hex,16);if(decimal ==-1){ cout <<"无效的十六进制数!"<< endl;}else{showConversions(decimal);}break;}default: cout <<"无效选择!"<< endl;}}return0;}运行示例
========== 进制转换器 ========== 1. 十进制转其他进制 2. 二进制转十进制 3. 八进制转十进制 4. 十六进制转十进制 5. 退出 =============================== 请选择: 1 请输入十进制数: 255 ========== 进制转换结果 ========== 十进制: 255 二进制: 11111111 八进制: 377 十六进制: FF ================================ 案例17:日期计算器
案例描述
计算两个日期之间的天数差,判断是否为有效日期。
知识点
- 日期算法
- 闰年判断
- 逻辑运算
完整代码
#include<iostream>usingnamespace std;structDate{int year;int month;int day;};// 判断是否为闰年boolisLeapYear(int year){return(year %4==0&& year %100!=0)||(year %400==0);}// 获取某月的天数intgetDaysInMonth(int year,int month){int days[]={0,31,28,31,30,31,30,31,31,30,31,30,31};if(month ==2&&isLeapYear(year)){return29;}return days[month];}// 判断日期是否有效boolisValidDate(const Date& date){if(date.year <1|| date.month <1|| date.month >12|| date.day <1){returnfalse;}int maxDay =getDaysInMonth(date.year, date.month);return date.day <= maxDay;}// 计算从公元1年1月1日到指定日期的天数intdateToDays(const Date& date){int days =0;// 计算年份的天数for(int y =1; y < date.year; y++){ days +=isLeapYear(y)?366:365;}// 计算月份的天数for(int m =1; m < date.month; m++){ days +=getDaysInMonth(date.year, m);}// 加上日期 days += date.day;return days;}// 计算两个日期之间的天数差intdaysBetween(const Date& date1,const Date& date2){returnabs(dateToDays(date1)-dateToDays(date2));}// 获取星期几(0=周日, 1=周一, ..., 6=周六)intgetDayOfWeek(const Date& date){// 使用蔡勒公式int y = date.year;int m = date.month;int d = date.day;if(m <3){ m +=12; y--;}int c = y /100; y = y %100;int w =(y + y/4+ c/4-2*c +(26*(m+1))/10+ d -1)%7;return(w +7)%7;}constchar*getWeekDayName(int dayOfWeek){constchar* names[]={"周日","周一","周二","周三","周四","周五","周六"};return names[dayOfWeek];}intmain(){ Date date1, date2; cout <<"========== 日期计算器 =========="<< endl; cout <<"请输入第一个日期(年 月 日): "; cin >> date1.year >> date1.month >> date1.day;if(!isValidDate(date1)){ cout <<"日期1无效!"<< endl;return1;} cout <<"请输入第二个日期(年 月 日): "; cin >> date2.year >> date2.month >> date2.day;if(!isValidDate(date2)){ cout <<"日期2无效!"<< endl;return1;}int days =daysBetween(date1, date2); cout <<"\n========== 计算结果 =========="<< endl; cout <<"日期1: "<< date1.year <<"年"<< date1.month <<"月"<< date1.day <<"日 "<<getWeekDayName(getDayOfWeek(date1))<< endl; cout <<"日期2: "<< date2.year <<"年"<< date2.month <<"月"<< date2.day <<"日 "<<getWeekDayName(getDayOfWeek(date2))<< endl; cout <<"相差天数: "<< days <<" 天"<< endl; cout <<"相差周数: "<< days /7<<" 周 "<< days %7<<" 天"<< endl;return0;}运行示例
========== 日期计算器 ========== 请输入第一个日期(年 月 日): 2024 1 1 请输入第二个日期(年 月 日): 2024 12 31 ========== 计算结果 ========== 日期1: 2024年1月1日 周一 日期2: 2024年12月31日 周二 相差天数: 365 天 相差周数: 52 周 1 天 案例18:汉诺塔问题
案例描述
经典的汉诺塔递归问题,将n个盘子从A柱移动到C柱。
知识点
- 递归思想
- 问题分解
- 算法设计
完整代码
#include<iostream>usingnamespace std;int moveCount =0;// 汉诺塔递归解法voidhanoi(int n,char from,char to,char aux){if(n ==1){ moveCount++; cout <<"第 "<< moveCount <<" 步: 将盘子 "<< n <<" 从 "<< from <<" 移动到 "<< to << endl;return;}// 将n-1个盘子从from移动到aux(借助to)hanoi(n -1, from, aux, to);// 将第n个盘子从from移动到to moveCount++; cout <<"第 "<< moveCount <<" 步: 将盘子 "<< n <<" 从 "<< from <<" 移动到 "<< to << endl;// 将n-1个盘子从aux移动到to(借助from)hanoi(n -1, aux, to, from);}// 计算最少步数intminSteps(int n){return(1<< n)-1;// 2^n - 1}intmain(){int n; cout <<"========== 汉诺塔问题 =========="<< endl; cout <<"请输入盘子数量: "; cin >> n;if(n <=0){ cout <<"盘子数量必须大于0!"<< endl;return1;}if(n >10){ cout <<"盘子数量过多,步骤会很多(2^"<< n <<"-1 = "<<minSteps(n)<<" 步)"<< endl; cout <<"建议输入10以内的数字"<< endl; cout <<"是否继续?(y/n): ";char choice; cin >> choice;if(choice !='y'&& choice !='Y'){return0;}} cout <<"\n理论最少步数: "<<minSteps(n)<<" 步"<< endl; cout <<"\n开始移动..."<< endl; cout <<"A柱(起始) -> C柱(目标),B柱(辅助)"<< endl; cout <<"=============================="<< endl; moveCount =0;hanoi(n,'A','C','B'); cout <<"\n=============================="<< endl; cout <<"完成!总共移动了 "<< moveCount <<" 次"<< endl;return0;}运行示例
========== 汉诺塔问题 ========== 请输入盘子数量: 3 理论最少步数: 7 步 开始移动... A柱(起始) -> C柱(目标),B柱(辅助) ============================== 第 1 步: 将盘子 1 从 A 移动到 C 第 2 步: 将盘子 2 从 A 移动到 B 第 3 步: 将盘子 1 从 C 移动到 B 第 4 步: 将盘子 3 从 A 移动到 C 第 5 步: 将盘子 1 从 B 移动到 A 第 6 步: 将盘子 2 从 B 移动到 C 第 7 步: 将盘子 1 从 A 移动到 C ============================== 完成!总共移动了 7 次 案例19:杨辉三角
案例描述
打印指定行数的杨辉三角(帕斯卡三角)。
知识点
- 二维数组
- 数学规律
- 格式化输出
完整代码
#include<iostream>#include<iomanip>usingnamespace std;voidprintPascalTriangle(int n){int triangle[100][100]={0};// 生成杨辉三角for(int i =0; i < n; i++){ triangle[i][0]=1;// 每行第一个数为1 triangle[i][i]=1;// 对角线上的数为1for(int j =1; j < i; j++){ triangle[i][j]= triangle[i-1][j-1]+ triangle[i-1][j];}}// 打印杨辉三角 cout <<"\n========== 杨辉三角 =========="<< endl;for(int i =0; i < n; i++){// 打印前导空格,使三角形居中for(int k =0; k <(n - i -1)*2; k++){ cout <<" ";}for(int j =0; j <= i; j++){ cout <<setw(4)<< triangle[i][j];} cout << endl;} cout <<"============================="<< endl;}// 计算组合数 C(n, k) = n! / (k! * (n-k)!)longlongcombination(int n,int k){if(k > n - k) k = n - k;// 优化计算longlong result =1;for(int i =0; i < k; i++){ result *=(n - i); result /=(i +1);}return result;}// 使用组合数公式打印voidprintPascalTriangleByFormula(int n){ cout <<"\n使用组合数公式:"<< endl;for(int i =0; i < n; i++){for(int k =0; k <(n - i -1)*2; k++){ cout <<" ";}for(int j =0; j <= i; j++){ cout <<setw(4)<<combination(i, j);} cout << endl;}}// 打印特定行voidprintRow(int row){ cout <<"第 "<< row +1<<" 行: ";for(int i =0; i <= row; i++){ cout <<combination(row, i)<<" ";} cout << endl;}intmain(){int n; cout <<"请输入杨辉三角的行数: "; cin >> n;if(n <=0|| n >30){ cout <<"行数应在1-30之间!"<< endl;return1;}printPascalTriangle(n); cout <<"\n杨辉三角的性质:"<< endl; cout <<"1. 每行首尾都是1"<< endl; cout <<"2. 每个数等于它上方两个数之和"<< endl; cout <<"3. 第n行的数字是组合数C(n-1, k)"<< endl; cout <<"4. 每行数字之和为2^(n-1)"<< endl;// 验证性质4 cout <<"\n验证:第 "<< n <<" 行数字之和 = ";longlong sum =0;for(int i =0; i < n; i++){ sum +=combination(n -1, i);} cout << sum <<" = 2^"<<(n-1)<<" = "<<(1<<(n-1))<< endl;return0;}运行示例
请输入杨辉三角的行数: 7 ========== 杨辉三角 ========== 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 ============================= 杨辉三角的性质: 1. 每行首尾都是1 2. 每个数等于它上方两个数之和 3. 第n行的数字是组合数C(n-1, k) 4. 每行数字之和为2^(n-1) 验证:第 7 行数字之和 = 64 = 2^6 = 64 案例20:字符画图形
案例描述
使用字符绘制各种图形(三角形、菱形、心形等)。
知识点
- 循环嵌套
- 空格控制
- 图形规律
完整代码
#include<iostream>usingnamespace std;// 直角三角形voidprintRightTriangle(int n){ cout <<"\n直角三角形:"<< endl;for(int i =1; i <= n; i++){for(int j =1; j <= i; j++){ cout <<"* ";} cout << endl;}}// 等腰三角形voidprintIsoscelesTriangle(int n){ cout <<"\n等腰三角形:"<< endl;for(int i =1; i <= n; i++){// 打印空格for(int j =1; j <= n - i; j++){ cout <<" ";}// 打印星号for(int j =1; j <=2* i -1; j++){ cout <<"*";} cout << endl;}}// 菱形voidprintDiamond(int n){ cout <<"\n菱形:"<< endl;// 上半部分for(int i =1; i <= n; i++){for(int j =1; j <= n - i; j++){ cout <<" ";}for(int j =1; j <=2* i -1; j++){ cout <<"*";} cout << endl;}// 下半部分for(int i = n -1; i >=1; i--){for(int j =1; j <= n - i; j++){ cout <<" ";}for(int j =1; j <=2* i -1; j++){ cout <<"*";} cout << endl;}}// 空心菱形voidprintHollowDiamond(int n){ cout <<"\n空心菱形:"<< endl;// 上半部分for(int i =1; i <= n; i++){for(int j =1; j <= n - i; j++){ cout <<" ";}for(int j =1; j <=2* i -1; j++){if(j ==1|| j ==2* i -1){ cout <<"*";}else{ cout <<" ";}} cout << endl;}// 下半部分for(int i = n -1; i >=1; i--){for(int j =1; j <= n - i; j++){ cout <<" ";}for(int j =1; j <=2* i -1; j++){if(j ==1|| j ==2* i -1){ cout <<"*";}else{ cout <<" ";}} cout << endl;}}// 心形voidprintHeart(int n){ cout <<"\n心形:"<< endl;// 上半部分for(int i = n /2; i < n; i +=2){// 左边空格for(int j =1; j < n - i; j +=2){ cout <<" ";}// 左边的心形for(int j =1; j <= i; j++){ cout <<"*";}// 中间空格for(int j =1; j <= n - i; j++){ cout <<" ";}// 右边的心形for(int j =1; j <= i; j++){ cout <<"*";} cout << endl;}// 下半部分for(int i = n; i >=1; i--){for(int j =0; j < n - i; j++){ cout <<" ";}for(int j =1; j <= i *2-1; j++){ cout <<"*";} cout << endl;}}// 矩形voidprintRectangle(int rows,int cols){ cout <<"\n矩形 ("<< rows <<"x"<< cols <<"):"<< endl;for(int i =0; i < rows; i++){for(int j =0; j < cols; j++){if(i ==0|| i == rows -1|| j ==0|| j == cols -1){ cout <<"* ";}else{ cout <<" ";}} cout << endl;}}intmain(){int choice, size;while(true){ cout <<"\n========== 字符画图形 =========="<< endl; cout <<"1. 直角三角形"<< endl; cout <<"2. 等腰三角形"<< endl; cout <<"3. 菱形"<< endl; cout <<"4. 空心菱形"<< endl; cout <<"5. 心形"<< endl; cout <<"6. 矩形"<< endl; cout <<"7. 显示所有图形"<< endl; cout <<"8. 退出"<< endl; cout <<"==============================="<< endl; cout <<"请选择: "; cin >> choice;if(choice ==8){ cout <<"再见!"<< endl;break;}if(choice ==7){ size =5;printRightTriangle(size);printIsoscelesTriangle(size);printDiamond(size);printHollowDiamond(size);printHeart(6);printRectangle(5,10);continue;} cout <<"请输入图形大小: "; cin >> size;if(size <=0|| size >20){ cout <<"大小应在1-20之间!"<< endl;continue;}switch(choice){case1:printRightTriangle(size);break;case2:printIsoscelesTriangle(size);break;case3:printDiamond(size);break;case4:printHollowDiamond(size);break;case5:printHeart(size);break;case6:{int cols; cout <<"请输入列数: "; cin >> cols;printRectangle(size, cols);break;}default: cout <<"无效选择!"<< endl;}}return0;}运行示例
========== 字符画图形 ========== 1. 直角三角形 2. 等腰三角形 3. 菱形 4. 空心菱形 5. 心形 6. 矩形 7. 显示所有图形 8. 退出 =============================== 请选择: 3 请输入图形大小: 5 菱形: * *** ***** ******* ********* ******* ***** *** *