计算机系统基础日志No.2

计算机系统基础日志No.2
测试并验证xx>=0在计算机中不恒为真*

一,源程序

#include <stdio.h>
#include <stdlib.h>

int sq(int x) {
    return x*x;
}

int main(int argc, char *argv[]) {
    int i;
    for (i = 1; i < argc; i++) {
	int x = atoi(argv[i]);
	int sx = sq(x);
	printf("sq(%d) = %d\n", x, sx);
    }
    return 0;
}

二,编译运行及出现的问题分析

在这里插入图片描述
lwh@lwh-virtual-machine:~$ touch sq.c
lwh@lwh-virtual-machine:~$ gedit sq.c
lwh@lwh-virtual-machine:~$ gcc sq.c
lwh@lwh-virtual-machine:~$ gcc sq.c -o sq
lwh@lwh-virtual-machine:~$ ./sq 12
sq(12) = 144
lwh@lwh-virtual-machine:~$ ./sq 65535
sq(65535) = -131071
溢出
65535的二进制代码0000 0000 0000 0000 1111 1111 1111 1111 为有符号int型,前16位为0,最高位为0
平方后的二进制代码应为32位全为1,而又为有符号int型,最高位为符号位为1,故为负
lwh@lwh-virtual-machine:~$ ./sq 40000
sq(40000) = 1600000000
lwh@lwh-virtual-machine:~$ ./sq 50000
sq(50000) = -1794967296
溢出,类似65535
lwh@lwh-virtual-machine:~$ ./sq 400000
sq(400000) = 1086210048
溢出
400000的代码为0110 0001 1010 1000 0000
平方后的二进制代码最高位为0,故为正
lwh@lwh-virtual-machine:~$ ./sq 500000
sq(500000) = 891896832
溢出,类似400000

三, 数的运算中的溢出问题

由于计算机中运算器的位数有限,它所能表示数的范围也就受到限制,运算过程中一旦超出这个限制,运算结果就会产生错误,这就是计算机的"溢出"问题。

一个n位无符号数,其最小值为0,最大值为(2的n次方) 。
例如,8位无符号数,所能表示的数的范围是0-255。
16位无符数,所能表示的数的范围是0~65535。

一个n位带符号数,其最小值为-(2的n-1次方) ,最大值为 +(2的n-1次方)。
例如,8位有符号数,所能表示的数的范围是-128~+127。

16位有符号数,所能表示的数的范围是-32768~+32767。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值