Al tener que enfrentar algún problema en este programa para desarrollar una calculadora, intenté hacer el cálculo para la operación matemática antes de la declaración de cambio. El resultado de la impresión solo solicita una entrada no válida en mi declaración predeterminada después de ingresar el valor y la operación matemática
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
// declare and initialise working storage
char function;
int num1, num2, sum, sub, multi, div, remainder;
// prompt user to enter 2 number
printf("Enter numbers and function: ");
scanf("%d%c%d", &num1, &function, &num2);
// calculation
sum = num1 + num2;
sub = num1 - num2;
multi = num1 * num2;
div = num1 / num2;
remainder = num1 % num2;
// print the result
switch(function)
{
case '+':
printf("The sum is %d\n", sum);
break;
case '-':
printf("The subtraction is %d\n", sub);
break;
case '*':
printf("The multiplication is %d\n", multi);
break;
case '/':
if(num2 ==0)
{
printf("Cannot divide by 0!\n");
}
else
{
printf("The div is %d\n", div);
}
break;
case '%':
if(num2 ==0)
{
printf("Cannot divide by 0!\n");
}
else
{
printf("The remainder is %d\n", remainder);
}
break;
default:
printf("Invalid Entry!!!!!\n");
break;
}
return 0;
}
Solución del problema
The %c reads a character, spaces and enters are characters too, %d waits only for an int input, thats why every time you want to give too different numbers you have to click enter or space, to let the programm understand to read the next int input. So, if you choose to give your inputs like this:1 + 3 the programm understands:
&num1 = 1, &num2 = 3, &function = (scpace).
If you choose to give your characters like this:1+3(enter) it will run proper but, that's a not friendly calculator.What you can do is:
printf("Enter numbers: ");
scanf("%d%d", &num1, &num2);// give 5(space)2 or 5(enter)2
scanf(%c,&enter); //&reads the enter
printf("Enter function: ");
scanf("%c",&funcion);
No hay comentarios:
Publicar un comentario