sicily_1000 A-B

題目

編程基礎(chǔ)題,就是輸入兩個(gè)數(shù)A、B然后獲得A-B的結(jié)果

代碼

簡(jiǎn)單版

// CopyRight (c) HuangJunjie@SYSU(SNO:13331087). All Rights Reserved.
#include<iostream>
using std::cin;
using std::cout;

int main() {
  int a, b;

  cin >> a >> b;
  cout << a - b << endl;

  return 0;
}

高精度版

// CopyRight (c) HuangJunjie@SYSU(SNO:13331087). All Rights
#include<stdio.h>
#include<string.h>

char* strrev(char* str) {
  char *h = str, *t = str, ch;
  while (*t++) {}
  t -= 2;
  while (h < t) {
    ch = *h;
    *h++ = *t;
    *t-- = ch;
  }
}

void substruct(char *big, char *small, char* result) {
  for (int i = 0; big[i] || small[i]; i++) {
    if (big[i] < small[i]) {
      big[i] += 10;
      big[i + 1]--;
    }
    if (!small[i]) small[i] += '0';
    result[i] = (big[i] - '0') - (small[i] - '0') + '0';
  }
}

void Printf(char *c) {
  int i = 0;
  while (c[i++] == '0') {}
  if (!c[i]) printf("0");
  printf("%s", c + i - 1);
  printf("\n");
}

int main() {
  char a[100 + 1] = { 0 }, b[100 + 1] = { 0 }, c[100 + 1] = { 0 };
  scanf("%s", a);
  scanf("%s", b);
  strrev(a);
  strrev(b);
  if (strlen(a) < strlen(b)) {
    substruct(b, a, c);
    printf("-");
  } else if (strlen(a) > strlen(b)) {
    substruct(a, b, c);
  } else {
    for (int i = strlen(a) - 1; i >= 0; i--) {
      if (a[i] == b[i]) {
        if (i) {
          continue;
        } else {
          c[i] += '0';
        }
      } else if (a[i] > b[i]) {
        substruct(a, b, c);
        break;
      } else if (a[i] < b[i]) {
        substruct(b, a, c);
        printf("-");
        break;
      }
    }
  }
  strrev(c);
  Printf(c);
  return 0;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容