I am currently trying to make code for a calculator that will calculate the area of a
circle
,cube
, orsquare
, depending on which integer the user enters in the beginning, then prompt for the measurements, etc.
I want the user to choose between1
,2
, or3
.
My current code:
#include <stdio.h>
#include <math.h>
int main(void){
int shape;
printf("\nArea calculation\n(1) Square\n(2) Cube \n(3) Circle \nPlease make a selection");
scanf("%d", &shape);
else{
printf("\nIncorrect Choice");
}
return 0;
}
1
, 2
,3
. 99
then the program shuts off? You need to read and probably do a few c tutorials before you try to do this. These will get you started toward learning how to (1) print error output, (2) handle input, and (3) manage program control, which are the three things you seemed to ask about. There are a lot of ways to do this.
fprintf(stderr, "Error: incorrect value inputted. Please enter 1, 2, or 3.\n");
For input handling, you should google examples. Your scanf statement should end in a semicolon, not a colon. Statements in C end in a semicolon. Then you need some control flow to see what they entered and do something different based on that. A switch statement may make sense where, as here, you have a small number of options to deal with.
/* put in a function so we can call it from main() multiple times. */ int myFunction() { scanf("%d", &shape); switch(shape) { case 1: /* do stuff */ break; case 2: /* do stuff */ break; case 99: return 99; default: fprintf(stderr, "Incorrect Choice"); } }
Program Control. Finally, you want to be able to call this again if they fail. So put it in a function, and call that function from main.
int main() { /* this empty while loop will call myFunction() forever, */ /* or until it returns a 99 because someone quit. */ while(myFunction() != 99) ; }
This is a bit inelegant but should get you started. Again, you really, really want to start looking at tutorials on learning the language.