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

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

 

posted @ 2017-11-20 18:47  Bear_Guo  阅读(148)  评论(0编辑  收藏  举报