C++

发布于 2025-01-23 18:21:05 字数 242 浏览 3 评论 0原文

我是C ++的新手,我尝试了此简单的代码:

#include<iostream>
#include<math.h>
using namespace std;

int main(){
    double a;
    a=1/6;
    cout<<a;
}

但是结果是0。正如我所知,双重应与实数一起使用,因此结果不应该是1/6或0.1666666吗?谢谢你!

I am new to C++ and I tried this simple code:

#include<iostream>
#include<math.h>
using namespace std;

int main(){
    double a;
    a=1/6;
    cout<<a;
}

But the result is 0. As I understood, double should work with real numbers, so shouldn't the result be 1/6 or 0.1666666? Thank you!

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

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

发布评论

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

评论(2

长伴 2025-01-30 18:21:05

在表达式1/6 < / code>中,两个数字都是整数。这意味着该部门将执行整数部门,从而导致0。要进行double除法,例如,一个数字必须是双重:1.0/6

In the expression 1 / 6, both numbers are integers. This means that this division will perform integer division, which results in 0. To do a double division, one number has to be a double: 1.0 / 6 for example.

清秋悲枫 2025-01-30 18:21:05

整数文字16具有类型int。因此,在表达式中

1/6

使用了整数算术,结果等于0。

将至少一个操作数用作浮动文字。例如

a = 1.0/6;

a = 1/6.0;

a = 1.0/6.0;

Integer literals 1 and 6 have type int. Thus in the expression

1/6

there is used the integer arithmetic and the result is equal to 0.

Use at least one of the operands as a floating literal. For example

a = 1.0/6;

or

a = 1/6.0;

or

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