下面的C程序只为加法(+),差(-),乘法(*)提供输出。 但是,当我尝试使用除法(/)和模数(%)时,程序只是关闭自身而没有给出任何错误。帮帮我,我是C编程的新手。
//A simple calculator.
#include<stdio.h>
#include<conio.h>
void main()
{
int a, b, sum, diff, rem, multi;
float div;
char character;
clrscr();
printf("Choose the character you want to use(+, -, *, /, %): ");
scanf("%c", &character);
switch(character)
{
case '+': //will be used for addition.
printf("Enter the first and second number: ");
scanf("%d %d", &a, &b);
sum = a+b;
printf("The sum of the %d and %d is %d", a, b, sum);
break;
case '-': //will be used for difference.
printf("Enter the first and second number: ");
scanf("%d %d", &a, &b);
diff = a-b;
printf("The difference between %d and %d is %d", a, b, diff);
break;
case '%': //will be used for modulus.
printf("Enter the first and second number: ");
scanf("%f %f", &a, &b);
rem = a%b;
printf("The remainder of %f and %f is %f", a, b, rem);
break;
case '*': //will be used for product of 2 no.
printf("Enter the first and second number: ");
scanf("%d %d", &a, &b);
multi = a*b;
printf("The multiplication of %d and %d is %d", a, b, multi);
break;
case '/': //will be used for the division.
printf("Enter the first and second number: ");
scanf("%f %f", &a, &b);
div = a/b;
printf("The division of %f and %f is %f", a, b, div);
break;
default:
printf("Error! character please retry");
}
getch();
}
答案 0 :(得分:0)
在%f
和int
情况下,您为/
变量使用%
格式说明符。
scanf("%f %f", &a, &b);
因此会调用未定义的行为。
将其更改为如下。
scanf("%d %d", &a, &b);
%f
用于读取float变量。
如果要将浮点结果用于除法,则需要将参数之一强制转换为浮点,而不是将其读取为float
。
div = (float)a/b;
答案 1 :(得分:0)
使用 / 和%时使用
scanf("%d %d", &a, &b);
代替
scanf("%f %f", &a, &b);
因为%f用于浮点var,而对于 /和%则使用%d
答案 2 :(得分:0)
您使用了错误的格式。在gcc中启用-Wall
并修复警告后,我得到了一个有效的程序。您还错过了答案\n
的{{1}}
printf()
测试输出:
#include <stdio.h>
int main(int argc, char **argv)
{
int a, b, sum, diff, rem, multi;
float div;
char character;
printf("Choose the character you want to use(+, -, *, /, %%): ");
scanf("%c", &character);
switch(character)
{
case '+': //will be used for addition.
printf("Enter the first and second number: ");
scanf("%d %d", &a, &b);
sum = a+b;
printf("The sum of the %d and %d is %d\n", a, b, sum);
break;
case '-': //will be used for difference.
printf("Enter the first and second number: ");
scanf("%d %d", &a, &b);
diff = a-b;
printf("The difference between %d and %d is %d\n", a, b, diff);
break;
case '%': //will be used for modulus.
printf("Enter the first and second number: ");
scanf("%d %d", &a, &b);
rem = a%b;
printf("The remainder of %d and %d is %d\n", a, b, rem);
break;
case '*': //will be used for product of 2 no.
printf("Enter the first and second number: ");
scanf("%d %d", &a, &b);
multi = a*b;
printf("The multiplication of %d and %d is %d\n", a, b, multi);
break;
case '/': //will be used for the division.
printf("Enter the first and second number: ");
scanf("%d %d", &a, &b);
div = a/b;
printf("The division of %d and %d is %f\n", a, b, div);
break;
default:
printf("Error! character please retry");
}
}