字符串和双精度的麻烦,等值后再得到一个数字
Troubles with string and double, get another number after equating
计算一个数字后,我需要得到这个数字的几个数字。我将其转换为字符串,并打印一个数字,但在一段代码中,它工作正确(只打印一个数字(,但是在我将其等同于另一个变量后,程序打印了 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
。
相关文章:
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何获取一个数字的前3位
- 我想做一个彼此不同但重复出现的数字
- 如何检查一个c++字符串中有多少相同的字符/数字
- 为什么有时我输入一个整数,程序将第一个输入的数字打印成十进制数?
- 将向量之间的数字放在另一个向量之间<vector>>如果两个数字的差值为 1
- CIN 仅在输入非数字值时跳过下一个 CIN
- 以C++输出一个数字三角形
- 形成一个斐波那契三角形,使得每个数字是上面左对角线或右对角线上两个数字的总和
- 为什么当我输入一个被接受的数字时,我的 do-while 循环没有中断?
- 一个C++程序,用于在输入位数时输出具有特定位数的 .txt 文件中的所有数字
- 在C++中编程,将 3 个数字发送到一个函数,然后计算这 3 个数字的平均函数
- 在使用堆栈为下一个最大数字编写代码时面临 SIGSEGV(分段错误)
- 找到 x^n 的所有组合,并检查它们的总和是否等于一个不包括相同数字的数字
- 是否有一个 std::set 函数来确定不超过数字 x 的最大元素?
- 将数字提高到一个巨大的指数
- 反转一个数字程序不起作用,为什么?
- 使用带有一个参数函数的递归找到数字的平方
- 为什么当我输入一个大数字时,输出会一遍又一遍地重复?
- 为什么断点显示数组的第二个值是一个大数字?额外学分工作