iT邦幫忙

0

請問為甚麼我這個程式一遇到輸入分子有負號就會計算錯誤? 該怎麼改呢?

#include <stdio.h>

int main(void) {

int a,b,c,d,r1,r2;
printf("Enter two fractions separated by a plus sign:");
scanf("%d/%d%d/%d", &a, &b, &c, &d);
r1=a*d+b*c;
r2=b*d;
printf("The sum is %d/%d", r1, r2);



return 0;

}

//Input Data:
//9/28+-20/17

//Except:
//Enter two fractions separated by a plus sign:The sum is -407/476

//Actual result:
//Enter two fractions separated by a plus sign:The sum is 28/0

看更多先前的討論...收起先前的討論...
1.輸入的資料也要一模一樣地寫出來, 省得別人猜, 浪費時間
2.就算註冊多個帳號, 還是會被認出來
ktro12 iT邦新手 5 級 ‧ 2020-09-30 08:46:00 檢舉
一個帳號一天只能問一個,所以想問只能再創了
解完新手任務就可以一天問兩題了
ktro12 iT邦新手 5 級 ‧ 2020-09-30 20:52:16 檢舉
好,謝謝
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

0
海綿寶寶
iT邦大神 1 級 ‧ 2020-09-30 15:15:42
最佳解答

scanf 那列加一個+後如下

scanf("%d/%d+%d/%d", &a, &b, &c, &d);

另外,點這裡是我這次鐵人賽唯一的一篇文章,喜歡的話左上角點 Like

ktro12 iT邦新手 5 級 ‧ 2020-09-30 20:53:56 檢舉

謝謝

0
richardsuma
iT邦大師 1 級 ‧ 2020-09-30 00:49:27

輸入 -2/3 1/2 結果是 -1/6
輸入 2/3 -1/2 結果是 1/6

程式沒有錯!

我要發表回答

立即登入回答