gpt4 book ai didi

c - 算术移位不适用于负数输入?知道我在这里做错了什么吗?

转载 作者:行者123 更新时间:2023-11-30 15:39:39 24 4
gpt4 key购买 nike

// 1.5 Exercise 6.cpp : main project file.

#include "stdafx.h"
#include <stdio.h>

int sra(int x, int n);

int main()
{
int intInputNum;

int finalValue1;
int finalValue2;

printf("Please enter a integer and program will shift the integer 2 places to right,\n it will give value for both arithmetic as well as Logical shift\n");
scanf("%d",&intInputNum);

finalValue1 = intInputNum >> 2;

finalValue2 = sra(intInputNum, 2);

printf("Logical %d \n Arithmetic %d\n", finalValue1, finalValue2);

return 0;
}


int sra(int x, int k)
{
int xsrl = (unsigned)x >> k;
unsigned mask = k ? ((1 << (8 * sizeof(int)-k)) - 1) : 0;
return (x < 0) ? mask | xsrl : xsrl;
}

示例运行:

Please enter a integer and program will shift the integer 2 places to right, it will give value for both arithmetic as well as Logical shift-500Logical -125Arithmetic 1073741823

为什么这没有显示正确的值?

最佳答案

该标准不保证任何事情(,要么是 << 案例中的未定义行为,要么是(您的)>> 案例中定义的实现)的转变对负左侧 (LHS) 参数的运算。

关于c - 算术移位不适用于负数输入?知道我在这里做错了什么吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21357181/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com