生成 1 ~ n 的累加和
#includeusing namespace std; // 编写函数 求 1 ~ n 的累加和 int calSum(int n){ int sum = 0; for (int i = 1; i <= n; i++) { sum += i; } return sum; } int main (){ int n; cout<< "请输入你要累加的数字" < > n; // 调用函数 int res = calSum(n); cout<< "1 ~ "<< 10 << "累加和为: " << res < 生成随机数组和打印数组函数 版本一: 单机版
#includeusing namespace std; #define M 10 // 编写打印数组的函数 void printArray(int arr[], int len){ cout<< "["; for (int i = 0; i < len; i++) { if (i==len-1) cout< 版本二: 函数的预先声明版本
#includeusing namespace std; #define M 10 void printArray(int arr[], int len); void generateArray(int arr[], int len, int min, int max); int main (){ int arr[M]; cout<< "赋值前------------------------------------------------------------------------" < 版本三: 分文件编程 demo65.h 函数的声明(只有声明没有实现)
#ifndef JINLOU_DEMO65_H #define JINLOU_DEMO65_H void printArray(int arr[], int len); void generateArray(int arr[], int len, int min, int max); int getArrayMax(int arr[], int len); #endif //JINLOU_DEMO65_Hdemo65.cpp 实现头文件中的 函数
#includeusing namespace std; #include "demo65.h" // 编写打印数组的函数 void printArray(int arr[], int len){ cout<< "["; for (int i = 0; i < len; i++) { if (i==len-1) cout< max) max = arr[i]; } return max; } 编写测试文件test11.cpp 只需要导入 .h 头文件即可
#include#include "demo65.h" using namespace std; int main (){ int arr[10]; generateArray(arr, 10, 1, 100); printArray(arr, 10); // 求生成随机数组的最大值 int max = getArrayMax(arr, 10); cout<< "max = "<< max < 修改CMakeLists.txt 目的是编译的时候一起参与编译
add_executable(test11 jinday16/test11.cpp jinday16/demo65.cpp) add_executable(可执行程序名 文件1 文件2 文件3...)欢迎分享,转载请注明来源:内存溢出
评论列表(0条)