如何避免使用数组
How do I avoid using arrays?
我的教授想让我们像这样写一个不使用数组或向量的程序:
写一个程序,使用函数计算并打印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
变量是一个运行总数。在你的任务中寻找相似之处。
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
我的建议是使用递归方法,该方法首先接受输入,询问是否有更多的输入。如果有更多的输入,它就会调用自己。如果没有更多的输入,它输出当前的汽车,然后返回到目前为止在一个结构中添加的和。
该方法的唯一问题是,它将输出输入的汽车与输入相反,但它不会在没有数组或文件的情况下这样做。
- 有没有办法避免全局数组
- 如何避免在类中显式指定静态数组的大小
- 将C 数组写成文件,避免创建std :: String
- 避免在函数调用中计算数组元素
- 避免针对不同的字符数组大小进行模板实例化
- 如何避免意外地按值而不是按引用获取数组元素
- 如何在将数组传递给 C++ 中的函数时避免堆栈溢出
- 创建字符数组,避免缩小范围
- 在将数组写入向量时避免复制
- 动态对象数组在C++和Java中有何不同?
- 创建动态数组后,"i"变量不知从何而来
- 定义静态全局数组以避免在函数中定义它
- 避免在数组订阅运算符中悬而未决的引用
- 这些数组类型有何不同
- 使用数组和函数时如何避免" undefined reference to ... ' "?
- 初始化数组时,我可以避免c++11移动吗
- 有没有办法避免数组到指针衰减
- 使用Objective-C和C++避免并行数组
- 如何避免字符串数组中的重复条目
- 字符数组的字符串长度大于其大小.如何避免