简体   繁体   English

Java误认为原始数据类型?

[英]Java mistaking primitive data types?

Problem: I can't store the number '600851475143'. 问题:我无法存储数字“ 600851475143”。 I realize this number is bigger than what an int can hold and is smaller than the maximum long value. 我意识到这个数字大于一个int可以容纳的值,并且小于最大long值。 However, my program isn't registering the variable "number" as a long, it is registering it as a int. 但是,我的程序没有将变量“ number”注册为很长的时间,而是将其注册为int。 Can someone shed some light onto this problem? 有人可以阐明这个问题吗?

** - Line of the problem **-问题所在

public class Problem3{
//What is the largest prime factor of the number 600851475143
public static void main(String[] args){
  ***long number = 600851475143 , total = 0;
    for(long x = (number-1)/2; x>1; x--)
      if(number%x == 0 && isPrime(x)) total += x;
    System.out.println(total);
}
private static boolean isPrime(long determine){
  for(long x = determine/2 - 1; x>1; x--)
    if(determine%x ==0) return false;
  return true;
}

} }

SOLUTION: As Jim said below, in order to of type long, one has to put a "L" or "l" at the end of the number. 解决方案:正如Jim在下面说的那样,要输入长号,必须在数字的末尾加上“ L”或“ l”。 "An integer literal is of type long if it ends with the letter L or l; otherwise it is of type int. It is recommended that you use the upper case letter L because the lower case letter l is hard to distinguish from the digit 1." “整数文字如果以字母L或l结尾,则类型为long;否则为int类型。建议使用大写字母L,因为小写字母l很难与数字1区分开。 ”。 - From Oracle site on Primitive types. -从Oracle网站上的原始类型。

A little more info: Java's L number (long) specification 更多信息: Java的L号(长号)规范

长字面量需要用结尾的“ L”表示,例如600851475143L

Put a small 'L' in this literal value: 在此字面值中输入一个小“ L”:

 600851475143L

The reason is: 原因是:

An integer literal is of type long if it ends with the letter L or l; 如果整数文字以字母L或l结尾,则其类型为long; otherwise it is of type int. 否则为int类型。 It is recommended that you use the upper case letter L because the lower case letter l is hard to distinguish from the digit 1. 建议使用大写字母L,因为小写字母l很难与数字1区分开。

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

You can use this notation too, to be more clear: 您也可以使用此表示法,以使其更清楚:

 600_851_475_143L

"my program isn't registering the variable "number" as a long, it is registering it as a int". “我的程序没有将变量“ number”注册太久,而是将其注册为int”。

That's not correct. 那是不对的。 You declared it as a long. 您声明它很长。 It's a long. 好长

What you must be getting is something quite different: a compile error on the constant 600851475143. Try 600851475143L. 您必须得到的是完全不同的东西:常数600851475143上的编译错误 。请尝试600851475143L。 I suggest that if you read the compiler error message more carefully you would have seen that. 我建议,如果您更仔细地阅读编译器错误消息,您会发现的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM