Tuesday, 9 October 2012

Mein Taschenrechner ist fertig!

So, I said I'd improve it a lot, but I thought I'd just start a new project. So here is a slightly improved - and the FINAL version - of my multifunctional calculator.

Original Code:
#include <stdio.h>
int getUserInput();
int main()
{
 char cOperator,
     cCarryOn,
     cAgain;
 float fFirst,
     fSecond,
     fResult;

  printf("Enter first number ");
  scanf(" %f", &fFirst);
   
  printf("Enter second number ");
  scanf(" %f", &fSecond);

  printf("First number is %f and second number is %f\n", fFirst, fSecond);
   
  printf("Is this what you want? (y/n) ");
  scanf("  %c", &cCarryOn);
  while (cCarryOn != 'y' && cCarryOn != 'n')
  {
      printf("Type either 'y' or 'n' (without quotation marks) ");
      scanf(" %c", &cCarryOn);
  }
  if (cCarryOn == 'n')
  {
      printf("Program will now start again.\n");
      main();
  }
  else
  {
      printf("OK, let's continue.\n");
  }
 
   
   printf("What operator? +, -, * or /? ");
   scanf(" %c", &cOperator);
   while (cOperator != '+' &&
        cOperator != '-' &&
        cOperator != '*' &&
        cOperator != '/')
   {
     printf("Try again ");
     scanf(" %c", &cOperator);
   }
   
  switch (cOperator)
  {
      case '+':
      fResult = fFirst + fSecond;
      break;
      case '-':
      fResult = fFirst - fSecond;
      break;
      case '*':
      fResult = fFirst * fSecond;
      break;
      case '/':
      fResult = fFirst / fSecond;
      break;
      default:
      printf("Ah... Something wrong happened. Program will now restart");
      main();
      break;
  }

  printf("The final answer is %f\n", fResult);
   
  printf("Perform another calculation? (y/n) ");
  scanf(" %c", &cAgain);
  while (cAgain != 'y' && cAgain != 'n')
  {
      printf("Type 'y' or 'n' (without quotation marks) ");
      scanf(" %c", &cAgain);
  }
  if (cAgain == 'y')
  {
      main();
  }
  printf("Thank you for using this calculator. Bye!");
  return 0;
}


Example of an interaction:
Enter first number 43
Enter second number 2
First number is 43.000000 and second number is 2.000000
Is this what you want? (y/n) d
Type either 'y' or 'n' (without quotation marks) y
OK, let's continue.
What operator? +, -, * or / ?/
The final answer is 21.500000
Perform another calculation? (y/n) y
Enter first number 23
Enter second number 2
First number is 23.000000 and second number is 2.000000
Is this what you want? (y/n) y
OK, let's continue.
What operator? +, -, * or / ?e
Try again /
The final answer is 11.500000
Perform another calculation? (y/n) y
Enter first number 43
Enter second number 2
First number is 43.000000 and second number is 2.000000
Is this what you want? (y/n) -
Type either 'y' or 'n' (without quotation marks) y
OK, let's continue.
What operator? +, -, * or / ?-
The final answer is 41.000000
Perform another calculation? (y/n) n
Thank you for using this calculator. Bye!

1 comment: