c语言 7-5

编写set_n函数,返回将无符号整数x的第pos位到第pos + n - 1 位的 n 位 设为1后的值。

1、

#include <stdio.h>

unsigned set_n(unsigned x, int pos, int n)
{
    int i;
    for(i = pos; i <= pos + n - 1; i++)
    {
        x = (x | 1 << i);
    }
    return x;
}

int main(void)
{
    unsigned x;
    int pos, i;
    puts("please input three nonnegative integers.");
    printf("x = "); scanf("%u", &x);
    printf("pos = "); scanf("%d", &pos);
    printf("i = "); scanf("%d", &i);
    
    printf("result: %u
", set_n(x, pos, i));
    return 0;
}

原文地址:https://www.cnblogs.com/liujiaxin2018/p/14786290.html