3
//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”似乎可以很好地运行代码。

4

2 回答 2

11

L后缀用于表示数字文字的类型long int。通常,如果您只是将值分配给变量,则没有必要,因为对于 C++11 §2.14.2 ¶2(特别是表 6),没有后缀的十进制整数文字将是第一种类型可以在或int之间表示它。1long intlong long int

因此,您不会冒险将值本身截断;但:

  1. 您确实对文字的类型有一定程度的不确定性(32768可能是 anint或 a long,取决于平台/编译器);
  2. 您可能会无意中为您的特定表达式获得错误类型的文字。

因此,您需要L在要确保文字类型为long(或更大)的上下文中指定;想到两个重要的案例:

  • 解决重载;如果你有一个函数的两个重载,一个 forint和一个 for ,并且即使你传递一个小数字,你也long想确保调用一个,你将不得不使用文字;longlong

    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!
    

    32767int文字(因为它小到可以容纳 a int),a是 a int,结果将是 a int,即使您分配给 a longa如果大到足以溢出您的计算,这可能是一个问题;通过指定long文字,您保证您将执行long乘法。

    long v=32767L*a; // now we are doing all the math with longs
    

    (这个问题实际上在除法和 FP 文字double更为常见,通常您必须指定float文字才能获得预期的“真正除法”行为)

    正如@chris建议的那样,在进行“大”位移时会出现一种更常见的情况(同类),例如:

    long long mask=1<<53;
    

    出现与上述相同的问题:1is an int, 53is an int,计算将使用ints 执行,导致溢出(尽管在这种特殊情况下,任何体面的编译器都会发出警告);这里正确的形式是:

    long long mask=1LL<<53; // LL is the suffix for long long
    

来到你的特定代码:拿走没有风险L;因为number已经是 a long,在进行模运算时无论如何2都会被提升为long(根据“通常的算术转换”、§5 ¶10 和 §4.5),所以这里L没有区别。

尽管如此,在许多情况下,保留“预期类型”的字面量并不是一个坏主意:它保证即使另一个操作数的类型由于某种原因更改为更窄的类型,计算仍将在预期的方式(不是模数会产生任何影响)。


  1. 整数文字的类型是表 6 中可以表示其值的相应列表中的第一个。 来自 C++11 标准的表,描述了用于整数文字的类型

于 2013-09-29T01:06:31.767 回答
0

在这种情况下,不需要它。

表示一个长值,这L意味着它保留更多空间,只是您的计算将超出正常整数的范围。

于 2013-09-29T00:52:40.280 回答