//Using the if-else
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main() {
long number = 0; // Store input here
cout << "Enter an integer less than 2 billion: ";
cin >> number;
cout << endl;
if(number % 2L == 0) // Test remainder after division by 2
cout << "Your number is even." // Here if remainder is 0
<< endl;
else
cout << "Your number is odd." // Here if remainder is 1
<< endl;
return 0;
}
这里,在第一个'if'条件下,为什么他们在2之后有'L'?去掉“L”似乎可以很好地运行代码。
最佳答案
L
后缀用于表示数字文字是 long int
类型。通常,如果您只是将值分配给变量,则没有必要,因为对于 C++11 §2.14.2 ¶2(尤其是表 6),没有后缀的十进制整数文字将是第一种类型可以在 int
、long int
或 long long int
之间表示。1
因此,您不要冒险让值本身被截断;但是:
- 您确实对文字的类型有一定程度的不确定性(
32768
可能是int
或long
,具体取决于平台/编译器); - 您可能会无意中为您的特定表达式获取错误类型的文字。
因此,您需要在上下文中指定 L
以确保文字类型为 long
(或更大);我想到了两个重要的案例:
解决过载问题;如果您有两个函数重载,一个用于
int
,一个用于long
,并且您希望确保调用long
一个如果您要传递一个小数字,则必须使用long
文字;void foo(int); void foo(long); foo(1); // <-- will call the first overload foo(1L); // <-- will call the second overload foo(32768); // <-- may call the first or the second overload, depending // from the specific platform foo(32768L); // <-- will call the second overload
但最重要的是:在做算术时避免意外;如果你执行例如像这样的乘法:
int a; ... long v=32767*a; // don't let the "long" fool you - 32767*a is evaluated as an int!
32767
是一个int
文字(因为它足够小以适合int
),a
是一个int
,结果将是一个int
,即使您分配给一个long
。如果a
大到足以溢出您的计算,这可能是个问题;通过指定一个long
字面量,您保证您将执行一个long
乘法。long v=32767L*a; // now we are doing all the math with longs
(这个问题实际上方式在除法和 FP 字面量中更常见,通常你必须指定
double
或float
字面量才能得到预期的“真正的 split ”行为)正如 @chris 所建议的,在进行“大”位移位时会出现一种更频繁的情况(同类),例如:
long long mask=1<<53;
呈现与上面相同的问题:
1
是一个int
,53
是一个int
,计算将使用int
执行,导致溢出(尽管在这种特殊情况下任何体面的编译器都会发出警告);这里正确的形式是:long long mask=1LL<<53; // LL is the suffix for long long
针对您的特定代码:去掉 L
没有风险;因为 number
已经是一个 long
,所以 2
在进行模运算时无论如何都会被提升为 long
(根据“通常的算术转换”,§5 ¶10 和 §4.5),所以这里 L
没有区别。
尽管如此,在许多情况下,保留“预期类型”的字面量并不是一个坏主意:它保证,即使其他操作数的类型由于某种原因更改为更窄的类型,计算仍然会以预期的方式完成(不是模数,它会有任何不同)。
-
The type of an integer literal is the first of the corresponding list in Table 6 in which its value can be represented.
关于c++ - 'L' 在这里有什么意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19073325/