Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Program 4.4; Calculator with for loop
- #include <stdio.h>
- #include <ctype.h>
- #include <stdbool.h>
- bool first = true;
- bool exited = false;
- long double eq = 0.0L;
- double op = 0.0;
- char operation, choice;
- long double calculate(long double eq, double op, char operation);
- bool cont();
- int main(void){
- // Welcome words
- printf("Hello, it\'s my calculator on C via for loop.\n");
- printf("Please choice your opeartion to do");
- for( ;; ){
- // Loop to choose operation
- printf("\n\t1. Plus\n\t2. Minus\n\t3. Multiplication\n\t4. Division\n\t5. Exit\nYour choice: ");
- scanf("%c", &operation);
- // Exit if user decided it
- if(operation == '5') {
- printf("\nBye :c\n");
- return 0;
- }
- for( ;; ) {
- // Main loop of calculations
- if((operation >= '6') || (operation <= '0')) {
- // Check on false operations
- printf("\nI don\'t know that command.\n");
- break;
- }
- if(first) {
- // Entering first number
- printf("\nEnter first value: ");
- scanf("%Lf", &eq);
- first = false;
- }
- // Entering second (next) number
- printf("\nAnd: ");
- scanf("%lf", &op);
- // Calculating
- eq = calculate(eq, op, operation);
- printf("\n = %Lf\n", eq);
- exited = cont();
- if(exited) {
- op = 0.0;
- eq = 0.0L;
- first = true;
- break;
- }
- }
- }
- return 0;
- }
- long double calculate(long double eq, double op, char operation) {
- switch(operation) {
- case '1':
- eq += op;
- break;
- case '2':
- eq -= op;
- break;
- case '3':
- eq *= op;
- break;
- case '4':
- eq /= op;
- break;
- }
- return eq;
- }
- bool cont() {
- printf("Do you want to continue? [n|y] ");
- scanf("%c", &choice);
- switch(tolower(choice)) {
- case 'y':
- exited = false;
- break;
- case 'n':
- exited = true;
- break;
- default:
- printf("\nI don\'t know that choice, try again.\n");
- cont();
- break;
- }
- return exited;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement