• 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

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

  • 相关阅读:
    Marketing learning-3
    xml文件的生成
    sharedPreferences
    Marketing learning-2
    图说不为人知的IT传奇故事-5-小型机之王
    Marketing learning-1
    图说不为人知的IT传奇故事-4-王安用一生来跟IBM抗衡
    图说不为人知的IT传奇故事-3-硅谷DNA创造者HP
    图说不为人知的IT传奇故事-2-IBM咬不动的胡桃
    图说不为人知的IT传奇故事-1-计算机新生
  • 原文地址:https://www.cnblogs.com/TadGuo/p/7867724.html
Copyright © 2020-2023  润新知