文章标题
来源:互联网 发布:西蒙网络模块接法图解 编辑:程序博客网 时间:2024/05/14 02:38
练习 3-4 在数的对二的补码表示中,我们编写的 itoa 函数不能处理最大的负数,即字长n 等于-2 -1 的情况。请解释其原因。修改该函数,使它在任何机器上运行时都能打印出正确的值。
#include <stdio.h>#include <string.h>void reverse(char []);void itoa(int , char []);int main(){ int n = -2147483648; char s[100]; itoa(n, s); printf("%s\n", s); return 0;}/* reverse : reverse string s in place */void reverse(char s[]){ int c, i, j; for(i = 0, j = strlen(s)-1; i < j; i++, j--){ c = s[i]; s[i] = s[j]; s[j] = c; }}void itoa(int n, char s[]){ int i, sign = 1; if(n < 0) sign = n; i = 0; do { s[i++] = abs(n%10) + '0'; } while((n /= 10) != 0); if(sign < 0) s[i++] = '-'; s[i] = '\0'; reverse(s);}
练习 4-2
对 atof 函数进行扩充,使它可以处理形如
123.45e-6
的科学表示法,其中,浮点数后面可能会紧跟一个 e 或 E 以及一个指数(可能有正负号) 。
#include <stdio.h>#include <ctype.h>#include <math.h>int pow1(int n){ int sum = 1; int i = 0; for(; i < n; i++) sum *= 10; return sum;}/* atof: convert string s to double */double atof(char s[]){ int i, sign; double val, power; int flag, index; for(i = 0; isspace(s[i]); i++) ; sign = s[i] == '-' ? -1 : 1; if(s[i] == '+' || s[i] == '-') i++; for(val = 0; isdigit(s[i]); i++) val = 10*val + s[i] - '0'; if(s[i] == '.') i++; for(power = 1; isdigit(s[i]); i++){ val = 10*val + s[i] - '0'; power *= 10; } if(s[i] == 'e' || s[i] == 'E') i++; else return sign*val/power; flag = s[i] == '-' ? -1 : 1; if(s[i] == '+' || s[i] == '-' ) i++; for(index = 0; isdigit(s[i]); i++) index = index*10 + s[i] - '0'; if(flag < 0) return sign*val/power/pow1(index); else return sign*val/power*pow1(index);}int main(){ char s[] = "+123.456e-4"; double n = atof(s); printf("%.4f\n", n); return 0;}
0 0
- 文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题 文章标题 文章标题 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 调用android系统浏览器
- 写给重新开始的自己(面试的第一天)
- CSS选择器
- 2.andriod 的常用设置
- 小程序-----JAVA代码实现文件内容的复制
- 文章标题
- 【索引】Geometric Computations in 2D:Exercises: Beginner
- hdoj2544
- 最短路 HDU杭电2544【dijkstra算法 || SPFA】
- 基于hadoop1.2.1的hive伪分布式安装
- mysql下载地址
- 给第三方apk进行系统签名的几种方式
- The Array |
- Problem F. √ (N im) -Gym 100345F-找规律+打表