• fill array, show arrary , reverse_array


    #include <iostream>
    using namespace std;
    
    int Fill_array(double arr[], int n)
    {
        int count = 0;
    
        cout << "Enter your price: "<< endl;
        for(int i =0; i < n; i++)
        {
            cin >> arr[i];
            if((i+1) == n)
                cout <<"Enough! You are a rich man!"<<endl;
            else if(!cin)
                break;
            count++;
        }
        return count;
    }
    
    void Show_array(const double arr[], int n)
    {
        cout << "Your price list below: " << endl;
        for (int i = 0; i < n; i++)
            cout << "Price #" << i+1 << ": "<< arr[i] << endl;
    
    }
    
    void Reverse_array(double arr[], int n)
    {
        cout << "OK! Your price is: " << endl;
        while(n--)
        {
            cout <<"$"<< arr[n] << endl;
        }
    }
    const int LEN = 5;
    int main()
    {
        double name[LEN];
        int ct = Fill_array(name, LEN);
        cout << "There are  " << ct << " cases of dirty money!"<<endl;
        Show_array(name, ct);
        Reverse_array(name, ct);
    }
    View Code

    sizeof(arr) / sizeof(double) 得到数组元素个数??

    arr[LEN] == `\0`;

    然后在for里用 i+1== LEN 来判断更容易理解,如果为true说明数组已经填满。

    一会用指针做一遍。


    #include <iostream>
    using namespace std;
    
    double *fill_array(double *ps, const double *pe)
    {
        while(ps!=pe)
        {
            if(!(cin >> *ps)) {
                cin.clear();
                while (cin.get() != '\n')
                    continue;
                cout << "Bad input!" << endl;
            }
            else if (*ps < 0)
                break;
            else ps++;
        }
        return ps;
    }
    
    void show_array(double *ps, const double *pe)
    {
        while (ps != pe)
        {
            cout << *ps << endl;
            ps++;
        }
        cout << "Good!" << endl;
    }
    
    double *revalue_array(double *ps, const double *pe, float n)
    {
        for(;ps != pe;ps++)
            *ps *= n;
        return ps;
    }
    
    const int ARSIZE = 5;
    int main()
    {
        double arr[ARSIZE];
        double *pt = fill_array(arr, arr + ARSIZE);
        cout << "Let's see what you have: " << endl;
        show_array(arr, pt);
        cout << "Let's change the value: " << endl;
        float factor = 1.5;
        double *pf = revalue_array(arr, pt, factor);
        show_array(arr, pf);
        cout << "OK! You are rich now! " << endl;
        return 0;
    }
    fill array, show array, revalue array

    指针还是方便,不需要复制数据,返回指针就可以了

  • 相关阅读:
    解决chrome console打印的信息一闪而过
    Docker 构建自定义镜像
    Docker 镜像、容器、仓库
    Docker 简介、下载安装
    执行yum list installed | grep xxx 命令时报错:未提供依赖perl-DBD-SQLite、perl-DBI
    SpringBoot 配置多种运行环境
    SpringCloud Config 分布式配置管理
    SpringCloud Sleuth+Zipkin 分布式链路追踪
    Dubbo 配置中心、元数据中心
    dubbo admin的使用
  • 原文地址:https://www.cnblogs.com/TadGuo/p/7867724.html
Copyright © 2020-2023  润新知