首页 > 编程语言 > 详细

数组和函数

时间:2018-11-06 23:12:15      阅读:173      评论:0      收藏:0      [点我收藏+]

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.\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;
}

技术分享图片

实际传入的是数组地址,这样有两个好处:

  • 节省空间
  • 降低数据破坏风险

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() != ‘\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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!