Java 长数字帮助

发布于 2024-11-01 20:07:53 字数 190 浏览 4 评论 0原文

所以在我的代码顶部我声明了变量 私人长计数器; 当我尝试给它一个非常长的数字时,它会给出一个错误,我正在尝试这样做 计数器 = 1111111111111111; 那是 16 个“1”,我不断收到错误“int 类型的文字 1111111111111111 超出范围”我做错了什么?

So at the top of my code I declared the variable
private long counter;
And when I try to give it a number that's really long it gives an error, Im trying to do this
counter = 1111111111111111;
Thats 16 "1"s and I keep getting the error "The literal 1111111111111111 of type int is out of range" what am I doing wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

帅哥哥的热头脑 2024-11-08 20:07:53

尝试如下:

counter = 1111111111111111l;

请注意,最后一个字符是字母“L”(当然是小写),而不是数字一。这是一个更清晰的示例:

counter = 2222222222222222L;

正如其他人指出的那样,大写“L”也可以使用,并且更加清晰。 Java 中的所有整数文字都被解释为 int,除非您在它们后面添加“L”(或“l”)后缀以告诉编译器将其解释为 long

文字浮点数也会发生类似的情况,默认情况下它们被解释为 double ,除非您在它们后面加上“f”后缀以告诉编译器将其解释为 float >。如:

double num1 = 1.0;  //1.0 is treated as a literal double
float num2 = 1.0;   //1.0 is still treated as a literal double; the compiler may complain about loss of precision
float num3 = 1.0f;  //1.0 is treated as a float, and the compiler is happy 

Try it like this:

counter = 1111111111111111l;

Note that the last character there is the letter 'L' (lowercase, of course), and not the number one. Here is a clearer example:

counter = 2222222222222222L;

As others have pointed out, an uppercase 'L' also works and is much more clear. All integer literals in Java are interpreted as ints unless you suffix them with an 'L' (or 'l') to tell the compiler to interpret it as a long.

A similar thing happens with literal floating-point numbers, which are interpreted as doubles by default unless you suffix them with an 'f' to tell the compiler to interpret it as a float. As in:

double num1 = 1.0;  //1.0 is treated as a literal double
float num2 = 1.0;   //1.0 is still treated as a literal double; the compiler may complain about loss of precision
float num3 = 1.0f;  //1.0 is treated as a float, and the compiler is happy 
未蓝澄海的烟 2024-11-08 20:07:53

java编译器默认将任何数字读取为整数。 11111111111 显然超出了整数范围。输入 counter=11111111111L; 让编译器正确读取值。

The java compiler reads any number as an integer by default. 11111111111 is obviously outside the range of an integer. Type counter=11111111111L; to get the compiler to read the value correctly.

卷耳 2024-11-08 20:07:53

问题是默认情况下数字文字是 int 。要使数字文字变长,您必须使用字母字符 l (小写 L)来结束它。所以:

long counter = 1111111111111111l;

在 C# 中你也可以使用大写的 L。我不确定 Java 是否如此。

The problem is that numeric literals are ints by default. To make the numeric literal a long you have to finish it with the alpha character l (lower-case L). So:

long counter = 1111111111111111l;

In C# you can also use an upper-case L. I'm not sure about Java.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文