zoukankan      html  css  js  c++  java
  • 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

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

  • 相关阅读:
    从VS转MyEclipse的15天使用体验
    JSP标签
    cookie实现自动登录
    js中substring和substr的用法
    用原生sql查询返回实体对象的方法
    @Column
    event.keyCode用法及列表
    jQuery的选择器中的通配符[id^='code']
    struts2中<s:radio>标签设置默认选中项
    在Struts2中实现登陆后跳转到登录前页面
  • 原文地址:https://www.cnblogs.com/TadGuo/p/7867724.html
Copyright © 2011-2022 走看看