C++编程思想 第1卷 第3章 创建复合类型 数组 指针和数组 探究浮点格式

浮点格式在C和C++有限的空间里存储非常大和非常小的数
float和double的数字位 分为段:指数、尾数和符号位

float用科学计数法存储数值

//: C03:printBinary.h
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Display a byte in binary
void printBinary(const unsigned char val);
///:~


//: C03:printBinary.cpp {O}
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
#include <iostream>
void printBinary(const unsigned char val) {
  for(int i = 7; i >= 0; i--)
    if(val & (1 << i))
      std::cout << "1";
    else
      std::cout << "0";
} ///:~


//: C03:FloatingAsBinary.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
//{L} printBinary
//{T} 3.14159
#include "printBinary.h"
#include <cstdlib>
#include <iostream>
using namespace std;


int main(int argc, char* argv[]) {
  if(argc != 2) {
    cout << "Must provide a number" << endl;
    exit(1);
  }
  double d = atof(argv[1]);
  unsigned char* cp = 
    reinterpret_cast<unsigned char*>(&d);
  for(int i = sizeof(double)-1; i >= 0 ; i -= 2){
    printBinary(cp[i-1]);
    printBinary(cp[i]);
  }
  fflush(stdin);
  getchar();
} ///:~

程序打印出不同浮点数的二进制形式
一般是浮点数ieee标准,有的编译器可能不遵守
检查argc的值确保给定了整数
如果要一个参数,argc的值应为2
没参数,argc为1
程序名是argv的第一个元素
程序失败,调用标准C的库函数exit()来终止程序
命令行取得参数使用 atof()将字符转换成double浮点数
地址把数转换成 unsigned char* 指针做字节数组
字节数组的每一个字节用printBinary()显示出来


输入
1.0


输出
1111000000111111000000000000000000000000000000000000000000000000

猜你喜欢

转载自blog.csdn.net/eyetired/article/details/80720967
今日推荐