【问题标题】:Warning: “conversion from 'double' to 'int', possible loss of data”警告:“从 'double' 转换为 'int',可能会丢失数据”
【发布时间】:2021-10-27 22:25:40
【问题描述】:

我正在做关于按位运算的 C++ 作业:如何使用“>>=”(右移)和“

输入:输入两个整数N和M(其中M为位数)。

输出:N >>= M 和 N

#include <stdio.h>
#include <conio.h>
#include <math.h>

int main(){
    
    /* M is the number of bits
       N is the variable that take the value of ShiftLeft and 
       ShiftRight */

    int N, M;
    double ShiftLeft, ShiftRight;

    printf("Enter integers N: ");
    scanf_s("%d", &N);

    printf("\nEnter integers M: ");
    scanf_s("%d", &M);

    // You can use: N <<= M OR N * pow(2,M)
    ShiftLeft = N * pow(2,M);    
    printf("\nThe value of N <<= M is: ");
    printf("%lf", ShiftLeft);

    // You can use: N >>= M OR N / pow(2,M)
    ShiftRight = N / pow(2,M);
    printf("\nThe value of N >>= M is: ");
    printf("%lf", ShiftRight);

    (void)_getch();
    return 0;
}

之后,这些是我的测试:

Enter integers N: 4
Enter integers M: 2
The value of N <<= M is: 16.000000 
The value of N >>= M is: 1.000000
Enter integers N: 9
Enter integers M: 12
The value of N <<= M is: 36864. 000000
The value of N >>= M is: 0.002197

所以现在,我想将结果的数据类型从double 更改为int;但是,如果我改变:

double ShiftLeft, ShiftRight;

进入:

int ShiftLeft, ShiftRight;

编译器会报错:

C4244 '=':从 'double' 转换为 'int',可能会丢失数据。

或:

警告 C4244:'initializing' : 从 'double' 转换为 'int', 可能会丢失数据。

我不知道0.002197怎么能变成0。

我尝试将所有double%lf 替换为int%d,结果大约为0.002197 到0。但我不知道这是正确的方法。

你能给我一些关于 WARNING C4244 的建议吗?

【问题讨论】:

  • 您期待什么?如果将浮点数转换为整数,则会丢失小数点后的所有内容。
  • 您是否知道使用浮点数和pow 函数对于计算 22 的幂是完全多余的?忘记这个问题的浮点数和pow,用1 &lt;&lt; M替换pow(2, M)
  • ...不,你没有浪费我们的时间。本网站的目的是提出问题并得到答案。

标签: c visual-c++


【解决方案1】:
  1. 右移需要floor-ing,因为整数不是小数部分。 2.你想打印双精度值,而不是扫描它们:
    ShiftLeft = N * pow(2,M);    
    printf("\nThe value of N <<= M is: ");
    scanf_s("%lf", ShiftLeft);

应该是

    ShiftLeft = N * pow(2,M);    
    printf("\nThe value of N <<= M is: %f\n", ShiftLeft);

完整代码:

int main(void){
    
    /* M is the number of bits
       N is the variable that take the value of ShiftLeft and 
       ShiftRight */

    int N, M;
    double ShiftLeft, ShiftRight;

    printf("Enter integers N: ");
    scanf("%d", &N);

    printf("\nEnter integers M: ");
    scanf("%d", &M);

    // You can use: N <<= M OR N * pow(2,M)
    ShiftLeft = N * pow(2,M);    
    printf("\nThe value of N <<= M is: %f\n", ShiftLeft);

    // You can use: N >>= M OR FLOOR(N / pow(2,M))
    ShiftRight = floor(N / pow(2,M));
    printf("\nThe value of N >>= M is: %f\n", ShiftRight);

    return 0;
}

https://godbolt.org/z/3cvGfTjfW

【讨论】:

    【解决方案2】:

    Double 有一个 52 位长度的尾数。将double 数字转换为 32 位时,需要截断部分位。这就是编译器警告的原因。如果您想安全起见,请仅使用整数类型进行操作,如果您正在尝试使用位运算符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多