C++作业:编写程序读取数组并通过另一个函数为元素加5
实现读取数组并给每个元素加5的C++程序
嗨,我来帮你搞定这个作业要求!下面是完整的可运行代码,我会一步步给你解释每个部分的作用,你直接复制到在线编译器就能跑起来:
/****************************************************************************** Online C++ Compiler. Code, Compile, Run and Debug C++ program online. Write your code in this editor and press "Run" button to compile and execute it. *******************************************************************************/ #include <iostream> #include <iomanip> using namespace std; // 定义给数组每个元素加5的函数 void addFive(int arr[], int size) { for (int i = 0; i < size; ++i) { arr[i] += 5; } } int main() { int size; // 读取数组大小 cout << "Enter the size of the array: "; cin >> size; // 动态分配数组内存(避免固定大小的限制) int* arr = new int[size]; // 读取数组元素 cout << "Enter " << size << " array elements:" << endl; for (int i = 0; i < size; ++i) { cout << "Element " << (i+1) << ": "; cin >> arr[i]; } // 调用函数给每个元素加5 addFive(arr, size); // 输出修改后的数组 cout << "\nArray elements after adding 5:" << endl; for (int i = 0; i < size; ++i) { cout << setw(4) << arr[i]; // setw用来格式化输出,让元素对齐 } cout << endl; // 释放动态分配的内存,避免内存泄漏 delete[] arr; return 0; }
关键部分解释:
addFive函数:这里数组参数int arr[]其实会退化为指针,所以函数内部对数组元素的修改会直接作用到原数组上,不需要返回值。遍历数组的每个元素,执行+=5操作就完成了要求。- 动态数组:用
new int[size]根据用户输入的大小创建数组,比固定大小的数组更灵活,适合作业里的交互场景。 - 内存释放:最后用
delete[] arr释放动态分配的内存,养成良好的编程习惯,避免内存泄漏。 - 格式化输出:
setw(4)来自<iomanip>头文件,能让输出的元素对齐,看起来更整洁。
运行示例:
Enter the size of the array: 3
Enter 3 array elements:
Element 1: 10
Element 2: 20
Element 3: 30Array elements after adding 5:
15 25 35
内容的提问来源于stack exchange,提问作者Kadiem Haider
相关产品推荐
相关产品推荐

