很奇怪,通过变量相加得到的大数输出不正确,但直接声明大数却可以正确输出。
#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 //输出
请教为什么同样是大数的输出,但是结果却不同?
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 tocount
, socount
is-727379968
.Appropriately change the operand to
long
which should solve your problemIn addition, it also depends on whether your
a_count_length
is big enough and whether it needs long to saveint+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.