问题描述
我想在 C++ 中实现一个大 int 类作为编程练习——一个可以处理大于 long int 的数字的类.我知道已经有几个开源实现,但我想自己编写.我正在尝试了解正确的方法是什么.
I'd like to implement a big int class in C++ as a programming exercise—a class that can handle numbers bigger than a long int. I know that there are several open source implementations out there already, but I'd like to write my own. I'm trying to get a feel for what the right approach is.
我了解一般策略是将数字作为字符串获取,然后将其分解为较小的数字(例如单个数字),并将它们放入数组中.此时,实现各种比较运算符应该相对简单.我主要关心的是如何实现加法和乘法.
I understand that the general strategy is get the number as a string, and then break it up into smaller numbers (single digits for example), and place them in an array. At this point it should be relatively simple to implement the various comparison operators. My main concern is how I would implement things like addition and multiplication.
我正在寻找一种通用的方法和建议,而不是实际的工作代码.
I'm looking for a general approach and advice as opposed to actual working code.
推荐答案
大型 int 类需要考虑的事项:
Things to consider for a big int class:
数学运算符:+、-、/、*, % 不要忘记你的班级可能在运算符,运算符可以是链式,即其中一个操作数可以是 int、float、double 等.
Mathematical operators: +, -, /, *, % Don't forget that your class may be on either side of the operator, that the operators can be chained, that one of the operands could be an int, float, double, etc.
I/O 操作符:>>, <<这是你在哪里弄清楚如何正确地从用户输入创建你的类,以及如何格式化输出.
I/O operators: >>, << This is where you figure out how to properly create your class from user input, and how to format it for output as well.
转化/转换:弄清楚你的大整数是什么类型/类别类应该可以转换为,并且如何正确处理转换.一个快速列表将包括双精度和浮点数,并且可能包括 int (有适当的界限检查)和复杂(假设它可以处理范围).
Conversions/Casts: Figure out what types/classes your big int class should be convertible to, and how to properly handle the conversion. A quick list would include double and float, and may include int (with proper bounds checking) and complex (assuming it can handle the range).
这篇关于如何在 C++ 中实现大 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!