简体   繁体   English

在C和C ++中编写代码的不同值

[英]Different values on writing the code in C and C++

I am solving a problem to find sum of all prime numbers till 2million, in C. I am continuously getting wrong answer (1179908154) but when i wrote the same code in c++, it gave the correct answer (142913828922). 我正在解决一个问题,找到所有素数的总和,直到200万,在C中。我一直得到错误的答案(1179908154)但是当我在c ++中编写相同的代码时,它给出了正确的答案(142913828922)。 Please tell me why is it so, thank you. 请告诉我为什么会这样,谢谢。

Here is my code 这是我的代码

void main()
{
    int i,j;
    unsigned long long sum;

    for(sum=2,i=3;i<=2000000;i+=2)
    {
        for(j=3;j*j<=i;j++)
            if(i%j==0)
                break;
        if(j*j>i)
            sum+=i;
    }
    printf("%d",sum);
}

I am on windows 7, 32 bit and using GNU GCC v4.7.1 我在Windows 7,32位并使用GNU GCC v4.7.1

%d tells printf to expect an int argument. %d告诉printf期望一个int参数。 sum is an unsigned long long . sum是一个unsigned long long This is undefined behaviour. 这是未定义的行为。 You probably want printf("%llu\\n", sum); 你可能想要printf("%llu\\n", sum); .

int isn't a suitable type to be storing values up to 20000000 ; int不是适合存储高达20000000值的类型; The implementation isn't required to be able to represent values beyond -32767 or 32767 using an int . 实现不需要能够使用int表示超出-3276732767值。 You probably want i and j to be an unsigned long (suitable to represent positive values up to 0xFFFFFFFFUL ) or an unsigned long long (suitable to represent positive values up to 0xFFFFFFFFFFFFFFFFULL ). 您可能希望ijunsigned long (适合表示高达0xFFFFFFFFUL正值)或unsigned long long (适合表示高达0xFFFFFFFFFFFFFFFFULL正值)。 If you're working with values beyond that, you might want to consider using an arbitrary precision arithmetic library such as gmplib . 如果您正在使用超出该值的值,则可能需要考虑使用任意精度算术库,例如gmplib

void main() isn't a valid entry point in C. You probably want int main() . void main()不是C中的有效入口点。您可能需要int main()

Change type of i and j to long ... and use %ld as format specifier. ij类型更改为long ...并使用%ld作为格式说明符。 In c your value is crossing range of integer. 在c中,您的值是整数的交叉范围。

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

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