[英]'Repeating calculator' program in C with swtich case and do while loop, not working after 1st compilation
#include <stdio.h>
int main()
{
char operator;
double num1, num2, sum, mult, div, subtract, percentage;
do
{
printf("Enter a operator :\n");
printf("Click '+' for Addition\n");
printf("Click '-' for Subtraction\n");
printf("Click '*' for Multiplication\n");
printf("Click '/' for Division\n");
printf("Click '%%' for Percentage\n");
printf("Click '0' for Exit\n");
scanf("%c", &operator);
printf("Enter any two numbers\n");
scanf("%lf%lf", &num1, &num2);
switch (operator)
{
case ('+'):
sum = num1 + num2;
printf("The sum of %.2lf and %.2lf is %.2lf\n", num1, num2, sum);
break;
case ('-'):
subtract = num1 - num2;
printf("The substraction of %.2lf and %.2lf is %.2lf\n", num1, num2, subtract);
break;
case ('*'):
mult = num1 + num2;
printf("The multiplication of %.2lf and %.2lf is %.2lf\n", num1, num2, mult);
break;
case ('/'):
div = num1 / num2;
printf("The division of %.2lf and %.2lf is %.2lf\n", num1, num2, div);
break;
case ('%'):
percentage = (num1 / num2) * 100;
printf("The percentage of %.2lf and %.2lf is %.2lf %%\n", num1, num2, percentage);
break;
default:
printf("Invalid number, try a valid number\n");
}
} while (operator!= '0');
return 0;
}
正如Johnny Mopp和Andreas Wenzel已經回答的那樣,您的scanf("%c", &operator);
調用從scanf("%lf%lf", &num1, &num2);
中讀取換行符 ( \n
); 在循環的前一次迭代中運行的。
您可以更改調用以在格式字符串中的%c
說明符之前包含一個空格,以允許scanf()
function 跳過輸入緩沖區中的任何前導空白字符。
它應該如下所示:
scanf(" %c", &operator);
此外,在乘法計算中,您使用了+
運算符而不是*
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.