整数除法始终为零

编程入门 行业动态 更新时间:2024-10-27 16:36:04
本文介绍了整数除法始终为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可能重复: C编程部门

可能我的问题很简单愚蠢。 我想存储一个部门的值,特别是 1 / x 其中 x 是一个整数值。

probably my question is very simple and stupid. I would like to store the value of a division, in particular 1 / x where x is a integer value.

int x = 17; double result = 1/x;

我尝试这样做,但我总是得到 0.000000 ... 我尝试输入固定在x中的值,例如 1/17 ,但总是得到相同的值..什么是错误?

I try to do it but I always get 0.000000 ... I try to enter a value fixed in x, for example 1/17 but always get the same value .. what's Wrong?

推荐答案

您正在进行整数除法。

尝试以下操作,它将按预期工作:

Try the following and it will work as expected:

int x = 17; double result = 1.0 / x;

表达式中 1 的类型你以上是 int ,而 x 的类型是int。当你执行 int / int ,你会得到一个int回来。您需要至少有一种涉及浮点的类型( float 或 double ),以便浮点除法发生。

The type of the 1 in the expression you have above is int, and the type of x is int. When you do int / int, you get an int back. You need at least one of the types involved to be floating point (float or double) in order for floating point division to occur.

与数学不同,C ++中的划分可以指截断的整数除法(你所做的)还是浮点除法(在我的例子中我做了什么)。小心这个!

Unlike in Mathematics, division in C++ can either refer to truncated integer division (what you did) or floating point division (what I did in my example). Be careful of this!

在我的例子中,我们明确地说明了 double / int - >双重。

In my example, explicitly what we have is double / int -> double.

更多推荐

整数除法始终为零

本文发布于:2023-11-26 19:38:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634928.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:除法   整数   为零

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!