CHAPTER 04:EX 07

本文介绍了一个名为Stash的结构体的设计与实现,该结构体用于存储双精度浮点数。文中详细展示了如何初始化Stash、增加元素、扩容、获取元素以及清理内存等操作,并通过一个实例演示了如何使用Stash来存储并打印25个连续的双精度数值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//7. Make a Stash that holds doubles. Fill it with 25 double
//values, then print them out to the console.

#ifndef SOLUTION07_H
#define SOLUTION07_H

struct Stash {
    
int quantity;
    
int index;
    
double *storage;

    
void initialize ();
    
void inflate (int increase);
    
int add (double n);
    
double fetch(int index);
    
void cleanup ();
};

#endif    //SOLUTION07_H
//7. Make a Stash that holds doubles. Fill it with 25 double
//values, then print them out to the console.

#include 
<iostream>
#include 
"solution07.h"
using namespace std;

const int increase = 25;

int main () {
    
double t = 25.1;
    Stash number;
    number.initialize();
    
for (int i = 0; i < 25; i++)
        number.add(t 
+ i);
    
for (i = 0; i < 25; i++)
        cout 
<< number.fetch (i) << ' ';
    cout 
<< endl;
    number.cleanup();
}
//7. Make a Stash that holds doubles. Fill it with 25 double
//values, then print them out to the console.

#include 
<iostream>
#include 
"solution07.h"    
using namespace std;

const int increase = 5;

void Stash::initialize () {
    quantity 
= 0;
    index 
= 0;
    storage 
= 0;
}

void Stash::inflate (int increase) {
    
int oldquantity = quantity;
    
int newquantity = oldquantity + increase; 
    
double *old = storage;
    storage 
= new double[newquantity];
    
for (int i = 0; i < oldquantity; i++
        storage[i] 
= old[i];
    delete []old;
    quantity 
= newquantity;
}

int Stash::add (double n) {
    
if (index >= quantity)
        inflate(increase);
    storage[index] 
= n;
    index
++;
    
return index;
}

double Stash::fetch(int index) {
    
return storage[index];
}

void Stash::cleanup () {
    cout 
<< "freeing storage..." <<endl;
    
int quantity = 0;
    
int index = 0;
    delete []storage;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值