gpt4 book ai didi

c++ - 在类中使用 tostring。 C++

转载 作者:行者123 更新时间:2023-11-28 04:25:07 25 4
gpt4 key购买 nike

在类中使用 tostring。

#include <iostream>
#include <iomanip>
#include <string>
#include <cassert>

using namespace std;

这是我的类 LargeInteger。我很确定这里的一切都是正确的。

class LargeInteger {
private:
int id;
int numDigits; // number of digits in LargeInt / size of alloc array
int* digits; // the digits of the LargeInt we are representing

public:
LargeInteger(int value);
~LargeInteger();
string tostring();
};

具有参数 int 值的类 LargeInteger 的构造函数。

LargeInteger::LargeInteger(int value)
{
// set this instance id
id = nextLargeIntegerId++;

numDigits = (int)log10((double)value) + 1;

// allocate an array of the right size
digits = new int[numDigits];

// iterate through the digits in value, putting them into our
// array of digits.
int digit;
for (int digitIndex = 0; digitIndex < numDigits; digitIndex++) {
// least significant digit
digit = value % 10;
digits[digitIndex] = digit;

// integer division to chop of least significant digit
value = value / 10;
}
}

析构函数

LargeInteger::~LargeInteger()
{
cout << " destructor entered, freeing my digits" << endl
<< " id = " << id << endl
//<< " value=" << tostring() // uncomment this after you implement tostring()
<< endl;
delete[] this->digits;
}

这就是我感到困惑的地方。我在这里放什么?我试过了,但我不知道要将 intValue 设置为什么才能获得我想要的值。

string LargeInteger::tostring()
{
string intValue;
//intValue = ??
return intValue;
}

主要功能

int main(int argc, char** argv)
{
// test constructors, destructors and tostring()
cout << "Testing Constructors, tostring() and destructor:" << endl;
cout << "-------------------------------------------------------------" << endl;
LargeInteger li1(3483);
cout << "li1 = " << li1.tostring() << endl;

return 0
}

最佳答案

查看构造函数,您的数据结构中的数字数组似乎是以相反顺序编码为二进制(值 0..9)的十进制数字序列。

因此 1992 将被编码为 2,9,9,1。

为了使数字可打印,您需要向其添加“0”。然后您需要从头到尾迭代并连接可打印版本。像这样的东西:

string LargeInteger::tostring()
{
string intValue;
for (int i=numDigits-1; i>=0; i--)
intValue += digits[i] + '0';
return intValue;
}

Online demo

建议1

除了将数字存储为整数数组,您还可以使用字符串,因为字符串可以包含任何二进制数据,包括“\0”。这将避免内存分配的麻烦。

如果你这样做,你也可以使用迭代器和算法并编写你的相同函数:

string LargeInteger::tostring()
{
string intValue(digits.size(),' ');
transform (digits.rbegin(), digits.rend(), intValue.begin(),
[](auto &x){ return x+'0'; }) ;
return intValue;
}

Online demo

建议2

请注意,您的构造函数不适用于负数,因为 log10()否定引发异常。

这可以用一个绝对数字来纠正:

 numDigits = (int)log10(abs((double)value)) + 1;

然而,对负数使用模数会得到一个负数。这意味着我们的 tostring() 需要更改为使用每个数字的绝对值,如果任何数字为负,则在数字的开头添加负号(参见 online demo here ).

一个更方便的方法是在类级别有一个符号标志(说明数字总体上是正数还是负数),并更改构造函数以确保数字始终为正数。

关于c++ - 在类中使用 tostring。 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54507223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com