c++ - 在 C++ 中从 double 转换为 int
问题描述
我在将值从 double 转换为 int 时遇到了一些麻烦。我把第十位值为1和2的数字换算后,换算的值实际上是减了1。有人可以帮我解决这个问题吗?
#include <iostream>
#include <cstring>
#include <cmath>
typedef char* BookName;
using namespace std;
class DecimalBookInfo
{
public:
DecimalBookInfo(char inName[], double number);
private:
BookName name;
double code;
bool verifyCode(double number);
};
int main()
{
char name[] = "TestBook";
DecimalBookInfo testBook(name, 230.1);
}
DecimalBookInfo::DecimalBookInfo(char inName[], double number)
{
// initiate new cstring
name = new char[strlen(inName)];
strcpy(name, inName);
if (verifyCode(number))
code = number;
else
{
cout << "Wrong code...\n";
exit(1);
}
}
bool DecimalBookInfo::verifyCode(double number)
{
double areaCode = floor(number);
cout << areaCode << endl;
double subCode = ((number - areaCode) * 100.0);
cout << static_cast<int>(subCode) << endl;
if (areaCode > 999 || areaCode < 100 ||
((subCode - 10) != 0))
{
return false;
}
return true;
}
结果是:
230 9 密码错误...
所以我不确定为什么会这样。230后面的数字应该是10。谢谢
解决方案
推荐阅读
- c# - 使用内部类作为列表中的 T
- css - 为任何屏幕分辨率居中单个图像
- r - R. How to create a new column, returning i based on another column in R
- java - Streams and obtaining and printing out a value from a custom class
- javascript - Why can't you swap the arrays of a 2D array by reference?
- mysql - 加密已经在 mysql 表中的数据
- cplex - Word generation in Cplex
- jquery - AngularJS ng-submit 在移动设备上不起作用
- amazon-web-services - 在 CentOS7 中 - 没有可用的软件包 aws-cfn-bootstrap
- javascript - 直接将数组作为参数传递时,数组对象属性为空