变量 - C++不能正确输出1000000000000
怪我咯
怪我咯 2017-04-17 14:38:59
0
2
388

很奇怪,通过变量相加得到的大数输出不正确,但直接声明大数却可以正确输出。

#include <string>
#include <iostream>
#include <algorithm>
#include <vector>

int main(void)
{
    std::string s;
    std::cin >> s;
    long n;
    std::cin >> n;

    int length = s.length();
    int a_count_length = std::count(s.begin(), s.end(), 'a');

    long count = a_count_length * int(n / length) + std::count(s.begin(), s.begin()+(n%length), 'a'); // 这里是大数 + 0
    std::cout << count << std::endl;

    long q = 1000000000000; // 直接声明大数
    std::cout << q << std::endl;
    return 0;
}

程序输入和输出结果是这样的:

a                // 输入
1000000000000    // 输入
-727379968       //输出
1000000000000    //输出

请教为什么同样是大数的输出,但是结果却不同?

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(2)
伊谢尔伦

a_count_length * int(n / length) + std::count(s.begin(), s.begin()+(n%length), 'a'); All operands here are int, so the result is int, overflow, and -727379968 is obtained. Then convert this value to long and assign it to count, so count is -727379968.

Appropriately change the operand to long which should solve your problem

In addition, it also depends on whether your a_count_length is big enough and whether it needs long to save

左手右手慢动作

int+int is still equal to int. You have to use long from the beginning. There is no use in converting the type of the result.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template