数组和函数
Posted geoffreyone
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数组和函数相关的知识,希望对你有一定的参考价值。
1. 数组作为参数
#include <iostream>
const int ArSize = 8;
int sum_arr(int arr[], int n);
int main()
{
int p{},m{},q{};
int cookies[ArSize] = {1, 2, 4, 8, 16, 32, 64, 128};
std::cout << cookies << " = array address";
int sum = sum_arr(cookies, ArSize); // 8个元素求和
std::cout << "Total cookies eaten :" << sum << std::endl;
sum = sum_arr(cookies, 4); // 前4个元素求和
std::cout << "Total cookies eaten " << sum << " cookies.
";
sum = sum_arr(cookies + 4, 4); // 后4个元素求和
std::cout << "Last four eaters eaten " << sum << " cookies.
";
}
int sum_arr(int arr[], int n)
{
int total = 0;
std::cout << arr << " = arr, ";
std::cout << sizeof arr << " = sizeof arr
";
for (int i = 0; i < n; i++) {
total += arr[i];
}
return total;
}
实际传入的是数组地址,这样有两个好处:
- 节省空间
- 降低数据破坏风险
2.数组填充
#include <iostream>
const int Max = 5;
int fill_array(double ar[], int limit);
void show_array(const double ar[], int n);
void revalue(double r, double ar[], int n);
int main() {
using namespace std;
double properties[Max];
int size = fill_array(properties, Max);
show_array(properties, size);
if (size > 0) { //判断输入的乘数是否有效,无效则重新输入
cout << "请输入:";
double factor;
while (!(cin >> factor)) {
cin.clear();
while (cin.get() != ‘
‘)
continue;
cout << "Bad input; Please input a new number:
";
}
revalue(factor, properties, size);
show_array(properties, size);
}
cout << "完成
";
cin.get();
cin.get();
return 0;
}
int fill_array(double ar[], int limit) {
using namespace std;
double temp;
int i;
for (i = 0; i < limit; i++) {
cout << "Enter value #" << (i + 1) << ": ";
cin >> temp;
if (!cin) { //如果输入无效字符
cin.clear();
while (cin.get() != ‘
‘)
continue;
cout << "Bad input; Please input a new number:
";
break;
} else if (temp < 0) { //如果输入负数
break;
}
ar[i] = temp; //类型正确,给数组赋值
}
return i;
}
void show_array(const double ar[], int n) //const可以防止程序对传入参数进行修改
{
using namespace std;
for (int i = 0; i < n; i++) {
cout << "Property #" << (i + 1) << ": $";
cout << ar[i] << endl;
}
}
void revalue(double r, double ar[], int n)
{
for (int i = 0; i < n; i++) {
ar[i] *= r;
}
}
以上是关于数组和函数的主要内容,如果未能解决你的问题,请参考以下文章
如何将此 JavaScript 代码片段翻译成 Parenscript?
错误代码:错误域 = NSCocoaErrorDomain 代码 = 3840“JSON 文本没有以数组或对象和允许未设置片段的选项开头。”