# 《明解C语言》笔记及课后习题答案 【第七章】

/*编写一个程序，确认只要没有发生高位溢出，则：

#include <stdio.h>
#include <limits.h>

int main(void)
{
unsigned uns_int;

puts("请输入一个整数：");

do{
scanf("%u",&uns_int);
if(uns_int > UINT_MAX)
printf("您输入的整型过大，请重新输入。");
} while (uns_int > UINT_MAX);

printf("把整数向左移动3位后其值等于其乘以2的指数幂后的值：%u = %u\n",uns_int << 3, uns_int*2*2*2);
printf("把整数向右移动3位后其值等于其乘以2的指数幂后的值：%u = %u",uns_int >> 3, uns_int/2/2/2);

return 0;
} 

/*---编写rrotate函数，返回无符号整数x右移n位后的值。

#include <stdio.h>

unsigned rrotate(unsigned x, int n){
return x >> n;
}

unsigned lrotate(unsigned x, int n){
return x << n;
}

int main (void){
unsigned uns_int;
int move_bits;

printf("请输入整数和移动位数：");
scanf("%d %d",&uns_int, &move_bits);

printf("%u向右移%d次后的值：%u\n",uns_int, move_bits, rrotate(uns_int, move_bits));
printf("%u向左移%d次后的值：%u",uns_int, move_bits, lrotate(uns_int, move_bits));

return 0;
} 

/*---编写set函数，返回将无符号整数x的第pos位设为1后的值。---*/

//二进制的最右边位为第零位。

#include <stdio.h>

unsigned set(unsigned x, int pos){
unsigned i = 1;

return x | (i << pos);
}

unsigned reset(unsigned x, int pos){
unsigned i = 1;

return x & ~(i << pos);
}

unsigned inverse(unsigned x, int pos){
unsigned i = 1;

return x ^ (i << pos);
}
int main(void)
{
unsigned i, pos;

printf("请输入整型数及要操作的位数：");
scanf("%u %u",&i ,&pos);

printf("将第%d位设为1后的值%d\n",pos,set(i, pos));
printf("将第%d位设为0后的值%d\n",pos,reset(i, pos));
printf("将第%d位取反后的值%d",pos,inverse(i, pos));

return 0;
} 

/*---编程确认对无符号整数执行算术运算不会发生数据溢出。---*/

#include <stdio.h>
#include <limits.h>

int main(void)
{
unsigned i, j;

printf("无符号整型的最大值为： %u\n",UINT_MAX);

puts("请输入一个整型数：");
scanf("%u", &i);

printf("将无符号整形最大值与输入整型数相加：%u",UINT_MAX + i);

return 0;
}

/*---从键盘输入float型，double型，long double型的变量，并显示其值。---*/

#include <stdio.h>

int main (void)
{
float fl;
double db;
long double ldb = 4.55;

puts("请依次输入三个浮点数：");
scanf("%f %lf",&fl, &db);
printf("float型：%f\ndouble型：%f\nlong double型：%Lf",fl, db, ldb);

return 0;
} 

/*---显示三种浮点型的长度---*/

#include <stdio.h>

int main(void)
{
float fl;
double db;
long double ldb;

printf("float length %d\ndoble length %d\nlong double length %d", (unsigned)sizeof(fl), (unsigned)sizeof(db), (unsigned)sizeof(ldb));

return 0;
} 

/*---输入一个实数作为面积，求面积为该实数的正方形的边长。---*/

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

int main(void)
{
int area;

puts("请输入一个正方形的面积：");
scanf("%d", &area);
printf("该正方形的边长为：%f",sqrt(area));

return 0;
} 

/*横向显示代码，以0.01为单位将float型变量由0.0递增为1.00的过程。*/

#include <stdio.h>

int main(void)
{
int i;
float x, j = 0;

for (i = 0; i <= 100; i++) {
printf("x = %f  ", j);
j+=0.01;
x = i / 100.0;
printf("x = %f\n",x);
}

return 0;
} 

10-16

06-03 7475
06-07 4699
06-02 2932
06-05 4518
06-12 1264
06-11 4424
06-01 1176
06-18 1068
06-12 2420
12-20 2581
06-11 1562
06-09 2741