题解 | #浮点数加法#
浮点数加法
https://www.nowcoder.com/practice/ddec753f446e4ba4944e35378ba635c8
#include <iostream> #include <cstring> #define MAX 1000 using namespace std; int add(char a[], char b[], char c[], bool msb_carry, int carry, bool isINT) { //msb_carry=true return carry //msb_carry=false set carry as new msb //isINT=true calc int ;false =calc frac int alen = strlen(a), blen = strlen(b); int array_max = max(alen, blen); int i, j, sum = 0; if (isINT) { //整数部分 c[max(alen, blen)] = '\0'; for (i = alen - 1, j = blen - 1; i >= 0 || j >= 0; i--, j--) { int adigit = (i >= 0 ? a[i] - '0' : 0); int bdigit = (j >= 0 ? b[j] - '0' : 0); sum = adigit + bdigit + carry; carry = sum / 10; c[max(i, j)] = sum % 10 + '0'; } } else { //小数部分 c[array_max] = '\0'; for (i = array_max - 1; i >= 0; i--) { int adigit = (i < alen ? a[i] - '0' : 0); int bdigit = (i < blen ? b[i] - '0' : 0); sum = adigit + bdigit + carry; carry = sum / 10; c[i] = sum % 10 + '0'; } } if (msb_carry) return carry; else if (carry == 1) { for (int k = strlen(c) + 1; k >= 1; k--) c[k] = c[k - 1]; c[0] = '1'; return 0; } else return 0; } void separate(char a[], char ai[], char af[]) { int alen = strlen(a); int i, f, d; for (i = 0; i < alen; i++) { if (a[i] == '.') break; else ai[i] = a[i]; } ai[++i] = '\0'; //ai末尾添0 d = i; for (f = 0; f <= alen - d; f++, i++) { af[f] = a[i]; } af[++f] = '\0'; //af末尾添0 } int main() { char a[MAX], b[MAX]; char ai[MAX], af[MAX]; char bi[MAX], bf[MAX]; char resi[MAX], resf[MAX]; scanf("%s", a); scanf("%s", b); separate(a, ai, af); separate(b, bi, bf); add(ai, bi, resi, false, add(af, bf, resf, true, 0, false), true); printf("%s.%s", resi, resf); }