计算完一个数后,我需要得到这个数的几位数字。我将其转换为字符串,并打印一个数字,但在一段代码中,它工作正常(仅打印一个数字),但在我将其等于另一个变量后,程序打印 2 位数字。
#include "stdafx.h"
#include <iostream>
#include <chrono>
#include <ctime>
#include <sstream>
using namespace std;
int main()
{
time_t seconds;
int res = 0;
seconds = time(NULL);
double nump = seconds;
cout.precision(45);
for (int i = 1; i <= 100; i++) {
nump = nump /10;
}
std::ostringstream strs;
strs.precision(55);
strs << nump;
std::string str = strs.str();
cout << str[str.size() - 9] << endl; // here we get a gidit from the string (e.g. 5)
res = str[str.size() - 9];
cout << res << endl; // here we get a number (e.g. 49)
system("pause");
return 0;
}
我无法理解发生了什么事。请帮忙!
最佳答案
那是因为这里
res = str[str.size() - 9];
您将 char
的值存储在 int
中。将相同的值发送到 std::cout
时与将其打印为 char
时,将其打印为 int
可能会产生不同的结果。对于整数 this调用运算符,而对于字符 this而是调用运算符。
在您的示例中,您的值可能为 '1'
(ASCII 格式为 49
)。当您将其打印为 char
时,它会打印 1
,而当您将其打印为 int
时,它会打印 49
>.
解决此问题的一种方法是将 int res
改为 char
。
关于c++ - 字符串和 double 的问题,等号后得到另一个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57785558/