如何避免使用数组

How do I avoid using arrays?

本文关键字:数组 何避免      更新时间:2023-10-16

我的教授想让我们像这样写一个不使用数组或向量的程序:

写一个程序,使用函数计算并打印n个把车停在车库的顾客的停车费

停车率:

  • 一个停车场收取最低5美元的停车费,最多可停放5小时。
  • 车库在超过五小时内,每小时或不足一小时收取每小时0.50美元的额外费用
  • 任何给定的24小时内的最高收费为$10.00。假设没有一辆车一次停在那里超过24小时。

您应该输入每个客户的停车时间。您的程序应该以简洁的表格格式打印结果,并计算和打印您的收据总数。

程序输出应该是这样的:

car------Hours------Charge
1--------2.00--------$5.00 
2--------5.00--------$5.00
3--------5.30--------$5.50
etc.
total: 3---12.30----$15.50

我只能做到这一步:

include <iostream>
include <conio.h>
include <cmath>
include <iomanip>
using namespace std;
double calculate(double);
int main()
{
    double hours,charge;
    int finish;
    double sumhours;
    sumhours=0;
    finish=0;
    charge=0;
    int cars;
    cars=0;
    do
    {
        cout<<"Enter the number of hours the vehicle has been parked: "<<endl;
        cin>>hours;
        cars++;
        sumhours+=hours;
        finish=cin.get();
        if(hours>24)
        {
            cout<<"enter a time below 24hrs."<<endl;
            cars--; 
            sumhours=sumhours-hours;
        }
    }
        while(finish!=EOF);
        double total=calculate(hours);
        cout<<total<<": "<<(cars-1)<<": "<<sumhours;

    while(!_kbhit());
    return 0;
}
double calculate(double time)
{
    double calculate=0;
    double fees;
    if(time<=5)
        return 5;
     if(time>15)
        return 10;
     time=ceil(time);
     fees=5+(.5*(time-5));
    return calculate;
}

因为这是作业,所以这里有一个算法:
1. 打印头。
2. 清除running total变量。
3.而不是结束文件
3.1读取一条记录。
3.2打印记录内容
3.3 将记录字段值添加到运行总数变量(提示!
提示!)3.4. 而
4. 输出运行总数变量。

您可能需要对运行总数变量做一些额外的计算,特别是对于平均值。

编辑1:运行总数变量 的示例
int sum = 0; // This is the running total variable.
const unsigned int QUANTITY = 23;
for (unsigned int i = 0; i < QUANTITY; ++i)
{
    cout << "Adding " << i << " to sum.n";
    sum += i;
}
cout << "Sum is: " << sum << "n";
cout.flush();

在这个例子中,数据'i'不被存储,只被使用。sum变量是一个运行总数。在你的任务中寻找相似之处。

编辑2:检测cin 输入结束的示例
char reply = 'n';
while (tolower(reply) != 'y')
{
   cout << "Do you want to quit? (y/n)";
   cout.flush();
   cin >> reply;
   cin.ignore(1000, 'n'); // Eat up newline.
}
cout << "Thanks for the answer.n";
cout.flush();

既然你不能使用数组或向量,我认为你应该打印每辆车的停车数据,因为它正在处理。伪代码:

While more cars:
    Read data for next car
    Calculate cost
    Print data
    Add to running totals
End while
Print totals

在每次迭代中,生成相关的输出,但不要将其流式传输到std::cout。相反,将其流式传输到std::stringstream对象。然后,最后,将该对象流式传输到std::cout。数学运算可以简单地通过维持输入值的运行累积来完成。

当然,这是假设在这个家庭作业中使用std::stringstream不会被认为是"作弊"。

您可以尝试将值存储在链表结构中,而不是数组中。链表非常适合动态存储。试试这个教程,http://www.cprogramming.com/tutorial/lesson15.html

我的建议是使用递归方法,该方法首先接受输入,询问是否有更多的输入。如果有更多的输入,它就会调用自己。如果没有更多的输入,它输出当前的汽车,然后返回到目前为止在一个结构中添加的和。

该方法的唯一问题是,它将输出输入的汽车与输入相反,但它不会在没有数组或文件的情况下这样做。