字符串和双精度的麻烦,等值后再得到一个数字

Troubles with string and double, get another number after equating

本文关键字:数字 一个 双精度 麻烦 字符串      更新时间:2023-10-16

计算一个数字后,我需要得到这个数字的几个数字。我将其转换为字符串,并打印一个数字,但在一段代码中,它工作正确(只打印一个数字(,但是在我将其等同于另一个变量后,程序打印了 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中。打印与int相同的值在发送给std::cout时可能产生与打印为char时不同的结果。对于整数,调用此运算符,而对于字符,则调用此运算符。

在您的示例中,您可能的值为'1'(在 ASCII 中49(。当你把它打印为char时,它会打印1,当你把它打印为int时,它会打印49

解决这个问题的一种方法是使int res成为char

相关文章: