c - 了解 double 和整数

标签 c

绝对的初学者程序员,想知道你是否可以帮助我理解一些结果和术语。我正在尝试遵循程序逻辑以及它如何计算出某些值。以下案例是尝试理解这些概念的示例。

#include <stdio.h>
void main ()
{
    int inum = 11;
    double dnum = 2.56;

    double dec_result;
    int int_result;

    dec_result = inum / 4 + (3.0 * inum) / 5;
    printf("value in dec_result is %.2f\n", dec_result);

    dec_result = (double) inum / 4 + (3 * inum) / 5;
    printf("value in dec_result is %.2f\n", dec_result);

    int_result = (int) dnum * 10 + 1;
    printf("value in int_result is %d\n", int_result);

    int_result = (int) (dnum * 10 + 1);
    printf("value in int_result is %d\n", int_result);

}

我在 Visual Basic 中运行它时知道结果。我正在努力了解它是如何解决的。

我的作品:
inumdnum 我认为是“值的名称”,可以与 x 或 y 互换使用。与 int_resultdec_result 相同。

第一个 dec_result 是 8.60

dec_result = inum / 4 + (3.0 * inum) / 5;
         11 (an integer) / 4 + (3.0 * 11) / 5
         11 (an integer) / 4 + (33.0) / 5

那我有点迷路了...2.75 + 6.6?

不知何故,由于 inum 是一个整数,如果写成分数,值将被截断。但是括号里剩下的inum是先乘后变成小数位的数?

它显示为由占位符指定并由数据类型指定的小数位。

第二个 dec_result 是 8.75

dec_result = (double) inum / 4 + ( 3 * inum) / 5;
       = as double is a cast operator you change inum from int to double, so therefore: 

       = (double) inum / 4 + (33) / 5;
Then   = inum/4 becomes 2.75 + 33/5

为什么33/5位变成了6位? 它显示为由占位符指定并由数据类型 double 指定的小数位。

int_result = (int) dnum * 10 + 1;
       = cast operator alters dnum a double to integer so 2.56 becomes 2

       = 2 * 10 + 1
       = 20 + 1
       = 21

应该是括号前指定的整数,%d 占位符表示提供不带小数点的数字值。

int_result = (int) (dnum * 10 + 1);

我得到: = (整数) (2.56 * 10 + 1) = (整数) (25.6 + 1) =(整数)(26.6) = 26

因为该值应该是括号前指定的整数,而且 %d 占位符表示提供的值是不带小数点的数字。

我的逻辑正确吗?

最佳答案

只有当两个操作数都是整数(整数/整数、整数+整数等)时,C 编译器才会进行整数运算,否则会进行浮点运算( double /整数、 double +整数等)

第一个结果:

11 (an integer) / 4 + (33.0) / 5

第一部分(11/4)是用整数运算计算的,所以答案是2 第二部分(33.0/5)是用浮点运算计算的,所以答案是6.6,和是8.6

第二个结果:

(double) inum / 4 + (33) / 5;

“(double) inum/4”是使用浮点运算计算的,所以答案是 2.75。 “33/5”是用整数算出的,所以答案是6,和是8.75

在以下内容中:

int_result = (int) dnum * 10 + 1;

首先将变量 dnum 转换为整数,因此使用整数运算:2 * 10 + 1 == 21

最后:

int_result = (int) (dnum * 10 + 1);

在这种情况下,首先计算“dnum * 10 + 1”,这是使用浮点运算完成的:2.56 * 10 + 1 == 26.6。然后强制转换 - (int) - 截断为 26。

关于c - 了解 double 和整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39751520/

相关文章:

c - Valgrind 提示调用 fgets

c - 如何在 C 中为以下代码调试段错误。我在许多函数以及 main 中使用了 malloc 和 free

mysql - c程序添加一个用户到mysql

c - 当我更改参数时数组会更改

c++ - 在内置类型上使用 typedef(或#defines)——有什么合理的理由吗?

c - pthread_join 函数在执行后杀死线程还是我们需要调用 pthread_cancel/pthread_exit?

c - 如何从函数返回指向数组的指针?

无法将 C 程序转换为 Ruby

c - 如何在 C double 中表示无穷大?

从 VB.net 调用 DLL 导致堆异常