gpt4 book ai didi

c++ - 在源代码中表示大数字以提高可读性?

转载 作者:IT老高 更新时间:2023-10-28 22:16:14 27 4
gpt4 key购买 nike

在用 C++ 或 C 编写的应用程序的源代码中,是否有更易读的方式来表示大数字?

我们以数字 2,345,879,444,641 为例,在 C 或 C++ 中,如果我们希望程序返回此数字,我们将执行 return 2345879444641

但这不是真的可读。

例如,在 PAWN(一种脚本语言)中,我可以执行 return 2_345_879_444_641 甚至 return 2_34_58_79_44_46_41,这两者都会返回数字 2,345,879,444,641 .

这对人眼来说更具可读性。

是否有对应的 C 或 C++?

最佳答案

使用当前编译器(C++14 或更高版本),您可以使用撇号,例如:

auto a = 1'234'567;

如果您仍然坚持使用 C++11,您可以使用用户定义的文字来支持以下内容:int i = "1_000_000"_i。代码看起来像这样:

#include <iostream>
#include <string>
#include <cstdlib>

int operator "" _i (char const *in, size_t len) {
std::string input(in, len);
int pos;

while (std::string::npos != (pos=input.find_first_of("_,")))
input.erase(pos, 1);

return std::strtol(input.c_str(), NULL, 10);
}

int main() {
std::cout << "1_000_000_000"_i;
}

正如我所写,它支持下划线或逗号互换,因此您可以使用其中之一,或同时使用两者。例如,“1,000_000”会变成 1000000

当然,欧洲人可能更喜欢“。”而不是“,”——如果是这样,请随意修改。

关于c++ - 在源代码中表示大数字以提高可读性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14220217/

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