尽管使用 long long int,但由于溢出而导致负面结果

Negative result due to overflow despite using long long int

尽管使用了 long long int 数据类型,为什么这个程序的结果是负的? 请帮我。我的代码如下:

#include <iostream>

#define percent 10

int main() {
    int A=200,B=400,C=150,D=210;
    long long int non_Zero_value_number;
    non_Zero_value_number=(percent*(A*B*C*D))/100;
    std::cout<< "Number of  value 10% = " << non_Zero_value_number << std::endl;
}

您也应该将其他整数声明为 long long int。

计算(A * B * C * D)returns一个负数,因为它们都是正整数,结果溢出int。这应该可以解决它:

long long int A=200,B=400,C=150,D=210,E=50,F=30;

另外,虽然从技术上讲并没有错,但通常 #define 变量都是大写的,所以很清楚它们的来源。乍一看,我心想,“他们在哪里声明百分比?”

#define PERCENT 10

那当然你还得改:

non_Zero_value_number=(PERCENT *(A*B*C*D))/100;

如果您确定变量总是取正整数,那么您可以使用 unsigned long long int,如下面的程序所示。正如您将变量命名为 non_Zero_value_number,这是有道理的。

#include<iostream>
#include<vector>
#include <stdio.h>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <sstream>
#define percent 10

using namespace std;

int main () {


    srand((unsigned) time(0));

unsigned long long int A=200,B=400,C=150,D=210,E=50,F=30;
   unsigned long long int non_Zero_value_number;
        non_Zero_value_number=(percent*(A*B*C*D))/100;
        cout<< "Number of  value 10% = " << non_Zero_value_number<<endl;
  return 0;
}

数字10100integer literals and A, B, C and D are of the type int. This means that the expression (percent*(A*B*C*D))/100 will use the int type and since the result does not fit into this type, the behavior is undefined:

When signed integer arithmetic operation overflows (the result does not fit in the result type), the behavior is undefined, — the possible manifestations of such an operation include:

  • it wraps around according to the rules of the representation (typically 2's complement),
  • [...]

这似乎发生在给定的程序中,导致负数。可以将其中一个涉及的变量转换为 long long int 并依赖 integer conversions and the specific operator precedences 来避免溢出,但最好完全避免这种情况并 declare/define variables/values 在表达式中用作 long long int 的。使用 LL 后缀定义 long long int 整数文字 (C++11).

代码示例(应用了一些重构):

#include <iostream>

#define PERCENT 10LL

int main()
{
    long long int A=200,B=400,C=150,D=210;
    long long int non_zero_value_number=(PERCENT*(A*B*C*D))/100LL;
    std::cout << "Number of  value 10% = " << non_zero_value_number << '\n';
}

您要么需要将要乘以 long 的变量之一声明,要么需要在乘法期间将其转换为 long。

正在将 1 个变量声明为 long: 做多 A = 200; 整数 B = 400, C=150, D=210, ...

将所有变量声明为 long: 多头 A = 200, B = 400, C=150, D=210, ...

在乘法过程中将变量 A 转换为 long: non_Zero_value_number=(百分比*((长)ABC*D))/100;

问题是 C++ 在将最终结果转换为 long 之前在 int 中进行所有计算。这意味着一旦 int 值超过 2147483647,您仍然需要处理 int 溢出(参见 https://docs.microsoft.com/en-us/cpp/c-language/cpp-integer-limits

因为 10 x 200 x 400 x 150 x 210 = 25200000000,你超出了 int 的限制几个数量级

注意:此问题与 link 中的问题非常相似(尽管是针对 C++ 而不是 C#):