将 float 转换为 int

发布于 2024-11-29 21:04:36 字数 133 浏览 5 评论 0原文

我有这样的作业,您必须从用户那里获取代表美元值的 float 类型的输入 例如

4.05,

所以我想将此浮点数转换为int,使其以分为单位,因此int的值应该是405,我需要在C中执行此操作,任何人都可以提供一些帮助吗?

I'm have this assignment where you have to get an input of type float from the user which represents a value in dollars
for example

4.05

so I want to convert this float to an int such that it becomes in cents so the value of the int should be 405 , I need to do this in C, anyone can provide some help ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

慈悲佛祖 2024-12-06 21:04:36

由于这是家庭作业,因此这里有一些引导性问题:

  1. 您需要将美元数字更改为美分。什么数学运算可以做到这一点?
  2. 您需要将该数学运算的结果转换为整数。如何将浮点数转换为整数? (提示:铸造)

Since this is homework, here are some leading questions:

  1. You need to change a number in dollars to cents. What mathematical operation would do that?
  2. You need to convert the result of that mathematical operation to an integer. How can you convert a float to an integer? (Hint: casting)
夏至、离别 2024-12-06 21:04:36

谷歌上的第一个结果是“float to int c”:http://www.cs。 tut.fi/~jkorpela/round.html。下次请谷歌一下!

First result on google with "float to int c": http://www.cs.tut.fi/~jkorpela/round.html. Next time, please google it !

坦然微笑 2024-12-06 21:04:36

这对于您的问题来说是偶然的,但如果您决定进一步发展您的编程生涯并想要编写涉及非整数金钱值的代码,那么使用某种 十进制浮点库以避免精度错误。

这是针对 Python 的,但解释了使用正确的十进制数字与货币的基本原理:

http://docs.python .org/library/decimal.html

在这个作业中,如果没有它,你可能会没事,但使用它和/或在课堂上提出它可能会为你的老师赢得一些额外的学分。 ;)

This is sort of incidental to your question but in case you should decide to go further with your programming career and want to code something that involves non-integer values of money, you're safest using some kind of decimal floating point library to avoid precision errors.

This is for Python but explains the rationale for using proper decimal numbers with currencies:

http://docs.python.org/library/decimal.html

In this assignment you'll probably be fine without it but using it and/or bringing it up in class might win a few extra credit points with your teacher. ;)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文