#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.\n";
sum = sum_arr(cookies + 4, 4); // 后4个元素求和
std::cout << "Last four eaters eaten " << sum << " cookies.\n";
}
int sum_arr(int arr[], int n)
{
int total = 0;
std::cout << arr << " = arr, ";
std::cout << sizeof arr << " = sizeof arr\n";
for (int i = 0; i < n; i++) {
total += arr[i];
}
return total;
}
实际传入的是数组地址,这样有两个好处:
#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() != ‘\n‘)
continue;
cout << "Bad input; Please input a new number: \n";
}
revalue(factor, properties, size);
show_array(properties, size);
}
cout << "完成\n";
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() != ‘\n‘)
continue;
cout << "Bad input; Please input a new number: \n";
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;
}
}
原文:https://www.cnblogs.com/geoffreyone/p/9879979.html