类型强制转换问题

Tails136 2008-10-14 02:26:59
#include "iostream.h"
void main()
{
float fDecpounds=0;
float fDecfrac=0;
int nPounds=0,nShillings=0,nPence=0;

cout<<"Enter decimal pounds: ";
cin>>fDecpounds;

nPounds = (int)(fDecpounds);

fDecfrac = fDecpounds-nPounds;
nShillings = (int)(fDecfrac*20);

fDecfrac = fDecfrac*20-nShillings;
nPence = (int)(fDecfrac*12);

cout<<"Equivalent in old notation: £"<<nPounds<<"."<<nShillings<<"."<<nPence<<endl;
}
代码如上,
问题:输入3.8
nShillings的值按道理是16,但输出15
我跟踪来一下问题出在 nShillings = (int)(fDecfrac*20);
fDecfrac的值为0.8,但(int)(fDecfrac*20); 值却是15????
为什么,要怎么真确输出呢?
...全文
120 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
koo8 2008-10-14
  • 打赏
  • 举报
回复
搂主,你输入0.8,4.8,5.8...10.8等都能出来16。唯独输入1.8,2.8,3.8就得15,晕啦!!!

这个问题确实很奇怪,期待高手解决。
dzc8866 2008-10-14
  • 打赏
  • 举报
回复
有点难搞噢,等待高手解决,请高手顺便讲讲float、int怎么存储,强制转换时候怎么截取;Up!
Tails136 2008-10-14
  • 打赏
  • 举报
回复
2楼3楼的为什么把我的代码重打了一边,输入3.8问题依旧存在
4楼的谢谢,要求必须是存在int型中的,而且我要获得整数位,有用,又解决方法吗?
giant1st 2008-10-14
  • 打赏
  • 举报
回复
把nShillings换成Float 就可以了,
Float 到 int 的转换 会丢失数据的。
diamond1983 2008-10-14
  • 打赏
  • 举报
回复

int main() {
float fDecpounds = 0;
float fDecfrac = 0;
int nPounds = 0, nShillings = 0, nPence = 0;

cout << "Enter decimal pounds: ";
cin >> fDecpounds;

nPounds = (int) (fDecpounds);

fDecfrac = fDecpounds - nPounds;
nShillings = (int) (fDecfrac * 20);

fDecfrac = fDecfrac * 20 - nShillings;
nPence = (int) (fDecfrac * 12);

cout << "Equivalent in old notation: £" << nPounds << "." << nShillings
<< "." << nPence << endl;
return 0;
Baocai3000 2008-10-14
  • 打赏
  • 举报
回复

//============================================================================
// Name : cast.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
using namespace std;

int main() {
float fDecpounds = 0;
float fDecfrac = 0;
int nPounds = 0, nShillings = 0, nPence = 0;

cout << "Enter decimal pounds: ";
cin >> fDecpounds;

nPounds = (int) (fDecpounds);

fDecfrac = fDecpounds - nPounds;
nShillings = (int) (fDecfrac * 20);

fDecfrac = fDecfrac * 20 - nShillings;
nPence = (int) (fDecfrac * 12);

cout << "Equivalent in old notation: £" << nPounds << "." << nShillings
<< "." << nPence << endl;
return 0;
}


Result:

Enter decimal pounds: 0.8
Equivalent in old notation: £0.16.0

65,211

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧