![](/img/trans.png)
[英]can anyone please explain me the need for & in the first code snippet
[英]to_string().length() giving incorrect results in c++. Can anyone please explain me this behavior?
#include <iostream>
using namespace std;
int main()
{
int n,t;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>t;
cout<<to_string(t).length();
}
return 0;
}
测试用例:
Input-123 //正确
输出 3
input-111111111111111111111111 //不正确
输出 10
Input-11111 //不正确
输出 1010
这很可能是由于 cin 在将 111111111111111111111111 分配给 t 时尽可能多地读取 int 引起的,请注意 111111111111111111111111 超出了 int 的容量大小,甚至超出了 long long int 的容量。 然后至于修复 output,将 endl 语句链接到 output 语句的末尾,如下所示:
cout << to_string(t).length() << endl;
如果您坚持让您的代码适用于超出容量的整数,那么您可能需要查看一些算术库,例如GMP 算术库
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.