【发布时间】: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 << M替换pow(2, M)。 -
...不,你没有浪费我们的时间。本网站的目的是提出问题并得到答案。
标签: c visual-c++