你爲什麼不以C
使用switch
情況:
char oper;
float num1,num2;
printf("Enter operator either + or - or * or/: ");
scanf("%c",&oper);
printf("Enter two operands: ");
scanf("%f%f",&num1,&num2);
switch(oper) {
case '+':
printf("%.1f + %.1f = %.1f",num1, num2, num1+num2);
break;
case '-':
printf("%.1f - %.1f = %.1f",num1, num2, num1-num2);
break;
case '*':
printf("%.1f * %.1f = %.1f",num1, num2, num1*num2);
break;
case '/':
printf("%.1f/%.1f = %.1f",num1, num2, num1/num2);
break;
default:
/* If operator is other than +, -, * or /, error message is shown */
printf("Error! operator is not correct");
break;
}
現在用if-else
:
//same code
scanf("%f%f",&num1,&num2);
if(oper=='+')
printf("%.1f + %.1f = %.1f",num1, num2, num1+num2);
else if(oper=='-')
printf("%.1f - %.1f = %.1f",num1, num2, num1-num2);
else if(oper=='*')
printf("%.1f * %.1f = %.1f",num1, num2, num1*num2);
else if(oper=='/')
printf("%.1f/%.1f = %.1f",num1, num2, num1/num2);
else
/* If operator is other than +, -, * or /, error message is shown */
printf("Error! operator is not correct");
使用[STRCMP(http://www.cplusplus.com/reference/cstring/strcmp/)比較字符串(不串地址,這將是不同的) – amdixon
像任何其他語言功能,您需要在使用它們之前實際學習字符串。 – Lundin
你能否詳細說明什麼是strcmp以及如何使用它? – REA98