有没有办法避免全局数组
Is there a way avoid a global array?
我为初学者C++类做的一项实验室作业涉及打印存储在数组中的一系列数字的平方根。程序本身是有效的,但我的老师不希望我们使用全局变量。
void assignValue(){
for (int x=0; x<10; x++){
int num;
num = rand() % 100 + 1;
if (num % 2 != 0){
num += 1;
}
arr[x] = num;
}
以下是的主要方法
int main() {
srand(static_cast<unsigned int>(time(0)));
assignValue();
for (int f = 0; f < 10; f++){
cout << f << setw(8) << right << arr[f];
float square = sqrt(arr[f]);
cout << setw(8) << right << fixed << setprecision(3) << square << endl;
}
arr是主方法之上的全局变量。
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <iomanip>
#include <cmath>
void assignValue(int arr[], size_t n) {
for (int i=0; i<n; ++i) {
int num;
num = std::rand() % 100 + 1;
if (num % 2 != 0) {
num += 1;
}
arr[i] = num;
}
}
int main() {
const size_t size = 10;
int arr[size];
std::srand(static_cast<unsigned int>(std::time(0)));
assignValue(arr, size);
for (int i = 0; i < size; ++i){
std::cout << i << std::setw(8) << std::right << arr[i];
float square = std::sqrt(arr[i]);
std::cout << std::setw(8) << std::right << std::fixed << std::setprecision(3) << square << std::endl;
}
return 0;
}
以下是对采用数组引用的函数的建议:
// headers omitted (you'll need additionally iomanip, ctime, cstdlib, cmath)
// The constant is necessary because the function takes
// a reference to an array *of this specific size*
const size_t ARR_SIZE = 10;
// Take a reference to the array (the array is not copied)
void assignValue(int (&arr)[ARR_SIZE])
{
for (int i = 0; i < ARR_SIZE; i++) {
int num = rand() % 100 + 1;
if (num % 2 != 0) {
num += 1;
}
arr[i] = num;
}
}
您可以简单地用调用函数
int main()
{
int arr[ARR_SIZE];
// [...]
assignValue(arr);
// ...
}
以下是一种更符合核心准则的方法,因为不需要指针或大小信息。
#include <cstddef>
#include <cstdlib>
template<typename T, std::size_t N>
void assignValue(T (&arr)[N])
{
for (auto &elem : arr) {
elem = rand() % 100 + 1;
if (elem % 2 != 0) {
elem += 1;
}
}
}
auto
main() -> int
{
constexpr const auto ARRAY_SIZE = 10;
int arr[ARRAY_SIZE];
assignValue(arr);
return 0;
}
相关文章:
- 乘以字符串/数组和全局数组
- 初始化与函数输入相关的全局数组
- 有没有办法避免全局数组
- 为什么 g++ 不优化局部数组而是优化全局数组?
- (C )创建可以从功能访问的动态全局数组/向量
- 全局数组在 C 代码中添加到头文件时没有"类型"
- 在标头中定义全局数组的模板技巧
- 在不使用For循环的情况下将数据从指向本地数组的指针传输到全局数组
- 删除全局数组时堆损坏
- 全局数组变量在线程中丢失值
- 如何将多个位图包含在全局数组列表中
- 引用到全局数组时更改了 C++ 数组内容
- 在线判断平台中的全局数组堆内存分配
- 定义静态全局数组以避免在函数中定义它
- atof更改全局数组的值
- C++/Qt如何声明和初始化对象的全局数组
- 静态全局数组中的函数
- 从函数返回指向全局数组的指针
- 无法在c++中为全局数组赋值
- 我需要破解一个c++编译器来发出和解释一个特定的类指针作为全局数组内的索引