题解 | #浮点数加法#
浮点数加法
https://www.nowcoder.com/practice/ddec753f446e4ba4944e35378ba635c8
#include <stdio.h> // 计算字符串长度: int Length(char a[]) { int n = 0; for (int i = 0; a[i] != '\0'; i++) { n++; } return n; } int main() { char a[100] = {'0'}; char b[100] = {'0'}; char c[100] = {'0'}; scanf("%s", a); scanf("%s", b); int len1 = Length(a); int len2 = Length(b); int i = 0, j = 0, k = 0; while (a[i] != '.') { i++; } while (b[j] != '.') { j++; }//判断整数位位数是否相同 if (i > j) {//第一组输入的数整数位长,将第二组前面补0到和第一组整数位位数相等 char d[100] = ""; int m; for (m = 0; m < i - j; m++) { d[m] = '0'; } for (int n = 0; n < len2; n++) { d[m] = b[n]; m++; } int len4 = Length(d); for (int p = 0; p < len4; p++) { b[p] = d[p]; } } else if (i < j) {//第二组输入的数整数位长,将第一组前面补0到和第二组整数位位数相等 char d[100] = ""; int m; for (m = 0; m < j - i; m++) { d[m] = '0'; } for (int n = 0; n < len1; n++) { d[m] = a[n]; m++; } int len4 = Length(d); for (int p = 0; p < len4; p++) { a[p] = d[p]; } } len1 = Length(a); len2 = Length(b); if (len1 > len2) {//将小数位短的补0到和小数位长的位数相等 k = len1 - 1; for (int l = len2; l < len1; l++) { b[l] = '0'; } } else { k = len2 - 1; for (int l = len1; l < len2; l++) { a[l] = '0'; } } for(int q=0;q<=k;q++) { c[q]='0'; } while (k != -1) {//从后往前逐位相加,满十进一 if (a[k] == '.') { c[k] = '.'; k--; } else { if ((a[k] - '0') + (b[k] - '0') +(c[k]-'0')> 9) { if (a[k - 1] == '.') { c[k - 2] = '1'; c[k] = '0' + ((a[k] - '0') + (b[k] - '0') + (c[k] - '0') - 10); } else { c[k - 1] = '1'; c[k] = '0' + ((a[k] - '0') + (b[k] - '0') +(c[k] - '0') - 10); } } else { c[k] = '0' + (a[k] - '0') + (b[k] - '0')+(c[k] - '0'); } k--; } } printf("%s\n", c); return 0; }