I'm doing one of the beginner C-programming exercises, building a simple calculator that shows the menu, takes in the user's choice of operation, takes in 2 operands and shows the result. Here's what I have so far:
#include<stdio.h> int main(){ int add (int a,int b) {return a+b;} int substract (int a,int b) {return a-b;} int multiply (int a,int b) {return a*b;} double divide (int a,int b) {return a/b;} int modulo (int a,int b) {return a%b;} int num1, num2, choice; printf ("======MENU=======\n"); printf ("1. Add\n"); printf ("2. Substract\n"); printf ("3. Multiply\n"); printf ("4. Divide\n"); printf ("5. Modulo\n"); printf ("Please, select your operation and press enter:\n"); scanf ("%d", &choice); switch (choice){ case 1: printf ("Please, enter the two operands separated by space and press enter:\n"); scanf ("%d %d", &num1, &num2); add (num1, num2); printf ("%d\n", add); break; case 2: printf ("Please, enter the two operands separated by space and press enter:\n"); scanf ("%d %d", &num1, &num2); substract (num1, num2); printf ("%d\n", substract); break; case 3: printf ("Please, enter the two operands separated by space and press enter:\n"); scanf ("%d %d", &num1, &num2); multiply (num1, num2); printf ("%d\n", multiply); break; case 4: printf ("Please, enter the two operands separated by space and press enter:\n"); scanf ("%d %d", &num1, &num2); divide (num1, num2); printf ("%lf\n", divide); break; case 5: printf ("Please, enter the two operands separated by space and press enter:\n"); scanf ("%d %d", &num1, &num2); modulo (num1, num2); printf ("%d\n", modulo); default: printf ("Invalid entry\n"); break; }; scanf ("%d"); return 0; } My issues with this code are:
- The program doesn't return the correct values. The addition option shows numbers over 4000000. Other operations do the same.
- The program should scan for an integer to be entered once the operation is complete and then end. However, it crashes once the integer has been entered.
dividefunction, despite returning adouble, will truncate the division. Use1.0 * a / bor similar instead. That also fixes the zerobcase. Your specific problem: you're attempting to print the addresses of functions; using an incorrect format specifier to do so. Your program behaviour is undefined.