亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如下代碼,例輸入:5+6回車,則系統會認為回車也是輸入值,則不是數字,怎么解決?

如下代碼,例輸入:5+6回車,則系統會認為回車也是輸入值,則不是數字,怎么解決?

C
長風秋雁 2023-03-18 13:09:39
// opertion#include <stdio.h>#include <conio.h>#include <ctype.h>int main(void){double number_1 = 0.0;char operition = 0;double number_2 = 0.0;printf("請輸入你需要計算的算式:");scanf("%lf %c %lf",&number_1,&operition,&number_2);if( (isdigit(number_1)) || (isdigit(number_2))){switch(operition){case '+':printf("=%1f",number_1 + number_2);break;case '-':printf("=%lf",number_1 - number_2);break;case '*':printf("=%lf",number_1 * number_2);break;case '/':if(number_2 == 0){if(number_1 < 0)printf("=-∞");else if(number_1 == 0)printf("你的除數與被除數都為零,無解");elseprintf("=∞");}elseprintf("%lf",number_1 / number_2);break;case '%':if(number_2 == 0)printf("\n你的被取模數為零,無解");elseprintf("=%ld",(long)number_1 % (long)number_2);break;default:printf("\n你輸入的運算符不正確。");break;}}elseprintf("\n你輸入的不是數字。");getchar();return 0;}
查看完整描述

2 回答

?
慕容森

TA貢獻1853條經驗 獲得超18個贊

f( (isdigit(number_1)) || (isdigit(number_2)))
這里有幾個錯。
isdigit() 參數必須是整型,不能用于 double.
邏輯或 用得不對,要 邏輯 與 才 說得過去,你需要 number_1 和 number_2 都是數字才可以。
|| 運算,一個是數字就滿足 if.
isdigit() 只能判斷1個字符。
如果 輸入 .2 + .3 就不能通過。
======
正確方法:
int k;
k=scanf("%lf %c %lf",&number_1,&operition,&number_2);
if (k == 3){
輸入數據格式正確,進入 switch() 等 判斷和計算
}


查看完整回答
反對 回復 2023-03-21
?
尚方寶劍之說

TA貢獻1788條經驗 獲得超4個贊

你的問題還不是“scanf()把回車作為輸入值的問題”,scanf()認為回車是輸入的結束。
程序不能得出正確的結果,原因在于:
scanf("%lf %c %lf",&number_1,&operition,&number_2);
這時,如果你輸入的第一個參數和第三個參數,如果不是數字型的就會出錯。
if( (isdigit(number_1)) || (isdigit(number_2)))
也有問題,首先 isdigit()用錯。函數原型為int isdigit(char c),要求參數為字符類型而不是f型。
其次(isdigit(number_1)) || (isdigit(number_2))應該是&&而不是||。
另外程序本身還存在一些問題,比如,兩個實型數求余怎么求?

查看完整回答
反對 回復 2023-03-21
  • 2 回答
  • 0 關注
  • 102 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號