So when I first input anything other than a number the program prints "Invalid number 1" and it reloop. The problem is: When it reloop and I enter everything that the program expect and then enter any key to repeat, I get this problem: I insert anything other than a number but this time it doesn't print "Invalid number one" it skips it and print "Insert an operator: Error". Basically I want this calculator to ask me to enter numbers and the +/*/-// only but when I don't do that it should show me "Invalid num 1" or "Invalid operator" or "Invalid num 2" and then ask me to repeat until I input the correct form and then it goes to execute the next line and so on!
Note: I just started learning C and I want to put everything that I've learnt so far into this calculator. If/else/switch/printf/scanf/do...while/while/for/int/float/char/break/continue/ those are the things I've learnt so far!
#include<stdio.h>
int
main ()
{
int num1, num2;
int rst;
char choice;
int a = 43, b = 42, c = 45, d = 47;
char i = a, f = b, g = c, h = d;
char choix, n;
do
{
printf ("\n\nPlease choice + or * or - or / for operater\n");
printf ("\nPlease insert first number: ");
scanf (" %d", &num1);
if (num1 != 0)
{
printf ("\nPlease insert an operater: ");
scanf (" %c", &choice);
}
else
{
printf ("Invalid number 1");
}
if (choice == a)
{
printf ("\nPlease insert second number: ");
scanf (" %d", &num2);
rst = num1 + num2;
printf ("%d + %d = %d", num1, num2, rst);
}
else if (choice == c)
{
printf ("\nPlease insert second number: ");
scanf ("%d", &num2);
rst = num1 - num2;
printf ("%d - %d = %d", num1, num2, rst);
}
else if (choice == b)
{
printf ("\nPlease insert second number: ");
scanf ("%d", &num2);
rst = num1 * num2;
printf ("%d * %d = %d", num1, num2, rst);
}
else if (choice == d)
{
printf ("\nPlease insert second number: ");
scanf ("%d", &num2);
rst = num1 / num2;
printf ("%d / %d = %d", num1, num2, rst);
}
else if ((isdigit (choice) || isalpha (choice)))
{
printf ("Invalid operator");
}
printf ("\nDo you want to enter another pair of numbers(Y/N): ");
scanf (" %c", &choix);
if (choix == 'n')
{
choix = 'N';
}
}
while (choix != 'N');
return 0;
}
Aucun commentaire:
Enregistrer un commentaire