if (response.ToLower() == "addition")
{
Console.Write("Enter a number: ");
double num1 = double.Parse(Console.ReadLine());
Console.Write("Enter another number: ");
double num2 = double.Parse(Console.ReadLine());
double addition = (num1) + (num2);
Console.WriteLine("The answer is {0}", addition);
if(!double.TryParse (num1, out addition))
{
Console.WriteLine("Try Again");
tryAgain = true;
}
I tried to use try parse to handle my unhandled exception and make the user go back and do it again if they dont input a number/ integer/ decimal. I am new to try parse and dont know how to use it properly, So i would like to ask for a way in which i could handle exceptions in the future as well
Here's an inline link to replit(https://replit.com/#NitikPaudel/Maths-Calculator-Upgraded#main.cs)
I'd try something like below:
if (response.ToLower() == "addition")
{
double num1;
double num2;
Console.Write("Enter a number: ");
if(!double.TryParse(Console.ReadLine().ToString(),num1)){
Console.WriteLine("Try Again");
tryAgain = true;
};
Console.Write("Enter another number: ");
if(!double.TryParse(Console.ReadLine().ToString(),num2)){
Console.WriteLine("Try Again");
tryAgain = true;
};
double addition = (num1) + (num2);
Console.WriteLine("The answer is {0}", addition);
}
Or if you would prefer a try/catch
if (response.ToLower() == "addition")
{
try{
Console.Write("Enter a number: ");
double num1 = double.Parse(Console.ReadLine());
Console.Write("Enter another number: ");
double num2 = double.Parse(Console.ReadLine());
double addition = (num1) + (num2);
Console.WriteLine("The answer is {0}", addition);
}
catch(Exception e){
Console.WriteLine("Try Again");
tryAgain = true;
}
}
The function TryParse is here to check if a value can be converted and to prevent the exception before it is thrown.
To handle exceptions, you can use try catch, example:
try {
// do the work
}
catch (Exception ex) {
// work with exception
}
View this documentation: https://www.tutorialsteacher.com/csharp/csharp-exception-handling
Related
I'm attempting to pass a value determined by one function to another function that comes after it. Essentially: Function 1 determines a value, lets say x. Then X is passed to another function that specifically displays X as text. It's in a separate function to be used by other functions who can also determine the value of X. However, i'm only getting 0 instead of the variable x. What is wrong here?
float fahToCel(int userInput)
{
float result = 0;
do
{
printf("\nPlease input your number in Fahrenheit units:");
scanf("%d", &userInput);
} while (result = 0);
result = (float)(((float)5.0f / (float)9.0f) * (float)(userInput - 32));
return result;
}
float celToFah(int userInput){
float result = 0;
do
{
printf("\nPlease input your number in Celcius units:");
scanf("%d", &userInput);
} while (result = 0);
result = (float)(((float)9.0f / (float)5.0f) * (float)(userInput + 32));
return result;
}
float displayResult(float result) {
printf("\nThe equivalent tempature is: %f\n", result);
return result;
}
void inputInformation() {
printf("1. Convert temperature input from the user in degrees Fahrenheit to
degrees Celsius.\n");
printf("2. Convert temperature input from the user in degrees Celsius to
degrees Fahrenheit.\n");
printf("3. Quit.\n ");
}
int main()
{
int menuChoice = 0;
int userInput = 0;
int result = 0;
while (1)
{
inputInformation();
printf("Please make a selection now:");
scanf("%d", &menuChoice);
switch (menuChoice)
{
case 1:
fahToCel(userInput);
displayResult(result);
break;
case 2:
celToFah(userInput);
displayResult(result);
break;
case 3:
return 0;
default:
printf("\nThat is not a choice!\n");
break;
}
}
}
You never assign the result to result. Change like this:
result = fahToCel(userInput);
displayResult(result);
For an assignment I was asked to create a small program which asks for the users input which determines the converter they wish to operate. My question is why doesn't the program ask for the users input, AFTER they have entered which convertor they wish to use (1 or 2). Instead of calling scanf, it just runs the entire statement in one go.
#include <stdio.h>
int main()
{
float cm;
float inches;
int operation;
printf("Hello and welcome to the Inches to Centimetres converter. \n");
printf("Choose from the options below by entering the corresponding number:\n");
printf("Inches to CM converter (1)\n");
printf("CM to Inches converter (2)\n");
scanf("&d", &operation);
if (operation == 1)
{
printf("Please enter the amount of Inches you wish to convert : \n");
scanf("%f", &inches);
cm = inches * 2.54;
if (inches <= 0)
{
printf("Invalid number");
}
else
printf("%f inches is equal to %f centimetres.", inches, cm);
}
else if (operation == 2);
{
printf("Please enter the amount of Centimetres you wish to convert : ");
scanf("%f", &cm);
inches = cm / 2.54;
if (cm <= 0)
{
printf("Invalid number");
}
else
printf("%f centimetres is equal to %f inches.", cm, inches);
}
}
Output
Two problems here. First:
scanf("&d", &operation);
There's a typo, "&d" should be "%d", and it's why you get prompted twice right away. You want:
scanf("%d", &operation);
Second is this:
}
else if (operation == 2);
{
The ; immediately ends the else block. So the block in braces will always run. Get rid of the ;
}
else if (operation == 2)
{
Better yet:
} else if (operation == 2) {
Formatting your braces this way will practically eliminate this type of error.
#include <stdio.h>
int main()
{
printf("Hi!\nWelcome!\nThis is an expression based calculator\ndeveloped by Sankasuvra Bhattacharya\n");
printf("that performs arithmetic operations on\ntwo numbers.\n");
float num1;
float num2;
float ans = 0.0;
char symbol;
char ask;
printf("Please type the expression you want to calculate: ");
if(scanf("%f%1s%f",&num1,&symbol,&num2) != 3)
{
printf("\nInvalid input! Please try again...\n\n");
/* want to restart main() again here */
}
else {
switch(symbol) {
case '+' : ans = num1 + num2;
break;
case '-' : ans = num1 - num2;
break;
case '*' :
case 'x' :
ans = num1 * num2;
break;
case '/' :
if(num2 == 0) {
printf("Division by zero is not possible!\nPlease try again...\n\n");
return main();
}
else {
ans = num1 / num2;
break;
}
default :
printf("\nInvalid input! Please try again...\n\n");
return main();
}
printf("The answer is %g\n",ans);
printf("\nTo use the calculator again, type 'Y'. ");
printf("To exit, type any other character...\n");
scanf("%s",&ask);
if (ask == 'y' || ask == 'Y') {
printf("\n");
main();
}
else {
printf("Thank you for using the program. Please give full marks.");
}
}
return 0;
}
To answer your question.
I would not recommend calling main.
You could create another function that has all you code.
Inside main, you call that function.
You can call a function inside that function (called recursion)
However, a simple loop could do the job.
do{
printf("Hi!\nWelcome!\nThis is an expression based calculator\ndeveloped by Sankasuvra Bhattacharya\n");
printf("that performs arithmetic operations on\ntwo numbers.\n");
float num1;
float num2;
float ans = 0.0;
char symbol;
char ask;
printf("Please type the expression you want to calculate: ");
if(scanf("%f%1s%f",&num1,&symbol,&num2) != 3)
{
printf("\nInvalid input! Please try again...\n\n");
}
else {
switch(symbol) {
case '+' : ans = num1 + num2;
break;
case '-' : ans = num1 - num2;
break;
case '*' :
case 'x' :
ans = num1 * num2;
break;
case '/' :
if (num2 == 0) {
printf("Division by zero is not possible!\nPlease try again...\n\n");
return main();
}
else {
ans = num1 / num2;
break;
}
default :
printf("\nInvalid input! Please try again...\n\n");
return main();
}
printf("The answer is %g\n",ans);
printf("\nTo use the calculator again, type 'Y'. ");
printf("To exit, type any other character...\n");
scanf("%s",&ask);
printf("\n");
}while(ask == 'y' || ask == 'Y') ;
printf("Thank you for using the program. Please give full marks.");
}
Edit: To answer the comment to this question what you want to do is:
while(scanf("%f%1s%f",&num1,&symbol,&num2) != 3)
{
printf("\nInvalid input! Please try again...\n\n");
}
And remove the else
EDIT2: Full code. Note that the expression cannot be more than 99 characters.
#include <stdio.h>
int main()
{
float num1;
float num2;
float ans = 0.0;
char symbol;
char ask;
char string[100];
do{
printf("Hi!\nWelcome!\nThis is an expression based calculator\ndeveloped by Sankasuvra Bhattacharya\n");
printf("that performs arithmetic operations on\ntwo numbers.\n");
printf("Please type the expression you want to calculate: ");
while(1){
fgets (string , 100 ,stdin);
if(sscanf( string, "%f%1s%f",&num1,&symbol,&num2)!=3)
printf("\nInvalid input! Please try again...\n\n");
else
break;
}
switch(symbol) {
case '+' : ans = num1 + num2;
break;
case '-' : ans = num1 - num2;
break;
case '*' :
case 'x' :
ans = num1 * num2;
break;
case '/' :
if (num2 == 0) {
printf("Division by zero is not possible!\nPlease try again...\n\n");
return main();
}
else {
ans = num1 / num2;
break;
}
default :
printf("\nInvalid input! Please try again...\n\n");
return main();
}
printf("The answer is %g\n",ans);
printf("\nTo use the calculator again, type 'Y'. ");
printf("To exit, type any other character...\n");
scanf("%s",&ask);
printf("\n");
}while(ask == 'y' || ask == 'Y') ;
printf("Thank you for using the program. Please give full marks.");
return 0;
}
#Kristjan Kica answer is good. I think you are using spaces in your input like 1 + 2.
According to manual page of scanf
All conversions are introduced by the % (percent sign) character. The format string may also contain other characters. White space
(such as blanks, tabs, or newlines) in the format string match any amount of white space, including none, in the input. Everything else
matches only itself. Scanning stops when an input character does not match such a format character. Scanning also stops when an input
conversion cannot be made.
Remove the spaces and try again.
Example:
1+2 should work by the changes mentioned in kristijan answer.
Edit:
Replace the line in #Kristjan Kica answer
while(ask == 'y' || ask == 'Y') ;
with
}while(ask == 'y' || ask == 'Y') ;
Edit 2:
Last closing } should be your main functions closing brace.
Finally solved it. All thanks to Kristjan Kica...
#include <stdio.h>
int main(void)
{
float num1;
float num2;
float ans;
char symbol;
char ask;
char string[100];
fflush(stdin);
printf("Hi!\nWelcome!\nThis is an expression based calculator\ndeveloped by
Sankasuvra Bhattacharya\n");
printf("that performs arithmetic operations on\ntwo numbers.\n");
printf("Please type the expression you want to calculate: ");
fgets (string , 100 ,stdin);
if(sscanf( string, "%f%1s%f",&num1,&symbol,&num2)!=3)
{
printf("\nInvalid input! Please try again...\n\n");
main();
}
else
{
switch(symbol) {
case '+' : ans = num1 + num2;
break;
case '-' : ans = num1 - num2;
break;
case '*' :
case 'x' :
ans = num1 * num2;
break;
case '/' :
if (num2 == 0) {
printf("Division by zero is not possible!\nPlease try again...\n\n");
return main();
}
else {
ans = num1 / num2;
break;
}
default :
printf("\nInvalid input! Please try again...\n\n");
return main();
}
printf("The answer is %g\n",ans);
printf("\nTo use the calculator again, type 'Y'. ");
printf("To exit, type any other character...\n");
scanf("%s",&ask);
printf("\n");
if (ask == 'y' || ask == 'Y')
{
main();
}
else {
return 0;
}
}
}
I am a bit new to c programming. For my project I have been tasked with developing a simple calculator that asks the user to input an option then that option declares what operation is to be performed (i.e. if the user enters 1, this corresponds to selecting the addition option which then allows the user to add two numbers they choose. I have the majority of the code worked out, but the catch is that I need the calculator to toggle between int and double variables. When the user enters 5, the calculator should now work with integers then if the user hits 5 again, the calculator switches back to doubles and vice versa so long as you want to switch back and forth. The calculator automatically works with doubles. So, more specifically, if I wanted to use integer variables, I would enter 5, then lets say I wanted to switch back to doubles, I should enter five and receive the message "Calculator now works with doubles." So here is my code thus far:
#include<stdio.h>
#include<math.h>
#include<stdbool.h>
int main()
{
int integermode, doublemode, m, a, b, sum2, difference2, product2,
quotient2;
double i, j, sum1, difference1, product1, quotient1;
printf("This program implements a calculator.");
while(m !=6) {
printf("Options:\n");
printf("1 - addition\n2 - subtraction\n3 - multiplication\n4 - division\n5 - toggle calculator type\n6 - exit program\n");
printf("Please enter your option: ");
scanf("%d", &m);
if(m > 6) {
printf("Invalid option.\n");
printf("Options:\n");
printf("1 - addition\n2 - subtraction\n3 - multiplication\n4 - division\n5 - toggle calculator type\n6 - exit program\n");
printf("Please enter your option: ");
scanf("%d", &m);
}
switch (m) {
case 1:
if (integermode == true) {
printf("Enter first term: ");
scanf("%d", &a);
printf("Enter second term: ");
scanf("%d", &b);
printf("The sum is: %d\n", a+b);
break;
}
if (integermode == false) {
printf("Enter first term: ");
scanf("%lf", &i);
printf("Enter second term: ");
scanf("%lf", &j);
printf("The sum is: %.15lf\n", i+j);
}
break;
case 2:
if (integermode == true) {
printf("Enter first term: ");
scanf("%d", &a);
printf("Enter second term: ");
scanf("%d", &b);
printf("The difference is: %d\n", a-b);
break;
}
if (integermode == false) {
printf("Enter first term: ");
scanf("%lf", &i);
printf("Enter second term: ");
scanf("%lf", &j);
printf("The difference is: %.15lf\n", i-j);
}
break;
case 3:
if (integermode == true) {
printf("Enter first term: ");
scanf("%d", &a);
printf("Enter second term: ");
scanf("%d", &b);
printf("The product is: %d\n", a*b);
break;
}
if (integermode == false) {
printf("Enter first term: ");
scanf("%lf", &i);
printf("Enter second term: ");
scanf("%lf", &j);
printf("The product is: %.15lf\n", i*j);
}
break;
case 4:
if (integermode == true) {
printf("Enter first term: ");
scanf("%d", &a);
printf("Enter second term: ");
scanf("%d", &b);
if (b != 0) printf("The quotient is: %d\n", a/b);
if (b == 0) printf("Cannot divide by zero!\n");
break;
}
if (integermode == false) {
printf("Enter first term: ");
scanf("%lf", &i);
printf("Enter second term: ");
scanf("%lf", &j);
if(j != 0) printf("The quotient is: %.15lf\n", i/j);
if(j == 0) printf("Cannot divide by zero!\n");
break;
}
case 5:
if (m = 5) {
integermode = true;
printf("Calculator now works with integers.\n");
}
if (m != 5) integermode = false;
}
}
return 0;
}
General improvements
First off, you should notice your main function is massive for what it needs to accomplish, and takes a ton of indent levels (when properly indented). That is mostly because you've got a ton of duplicated functionality. You could easily extract the code that asks for the input numbers into a function and reuse it, changing only the operation performed in each case. Or probably even better, you could ask for the input numbers as a part of the main while loop, and then perform a different operation with them depending on the operation mode you're in.
You're not using <math.h>, so you can leave it out.
Another thing I've noticed is you don't initialize the m variable before using it in the while loop. That could potentially cause a lot of problems, so you should initialize it to some value that isn't a valid mode, like for example 0 or -1.
You're also using two consecutive if statements when if/else could be used.
if (integermode == true) {
.....
}
if (integermode == false) {
.....
}
is the same as
if (integermode == true) {
.....
} else {
.....
}
but harder to read and less efficient, as you're doing two comparisons instead of one.
Implementation of double/integer modes
About the functionality you want to implement, you could very well define an enumeration with the possible modes:
typedef enum _datamode {
INTEGER_MODE,
DOUBLE_MODE
} data_mode;
and then have a variable holding the current mode:
data_mode datamode = INTEGER_MODE /* Initializing this to the default mode */
then use integers or doubles during the calculation and output depending on the current value of the variable. Of course, this could be done in a shorter way with an integer instead of an enum and a typedef, but I find this to be a more verbose way.
For the inputs and the result, you could use the union C type, which reserves memory for the biggest type you specify inside it and lets you store any of them in it. For example:
union io {
int i;
double d;
} a, b, result;
declares three variables that have the io union as type. That way, you can use them as integers or doubles as you like (as long as you don't mix types up and, for example, store an integer and read it as a double)
Full working implementation
The following would be my implementation of the program you have to do. It could be accomplished in a much shorter way (take into account the switches dealing with enums take a fair bit of the total space) but I think this is way more elegant and verbose.
I've respected your print statements and the flow of your application, even though I think they could be better (maybe this is something your assignment imposes on you?)
Please take this as an opportunity to learn and don't just copy-paste the code.
#include <stdio.h>
#include <stdlib.h>
typedef enum _datamode {
INTEGER_MODE,
DOUBLE_MODE
} data_mode;
typedef enum _operationmode {
ADDITION,
SUBSTRACTION,
MULTIPLICATION,
DIVISION,
TOGGLE,
EXIT
} operation_mode;
operation_mode ask_mode () {
int input = -1;
while (1) {
printf("Options:\n");
printf("1 - addition\n2 - subtraction\n3 - multiplication\n4 - division\n5 - toggle calculator type\n6 - exit program\n");
printf("Please enter your option: ");
scanf("%i", &input);
if (input < 1 || input > 6) {
printf("Invalid option.\n");
} else {
switch (input) {
case 1:
return ADDITION;
case 2:
return SUBSTRACTION;
case 3:
return MULTIPLICATION;
case 4:
return DIVISION;
case 5:
return TOGGLE;
case 6:
return EXIT;
default:
exit(EXIT_FAILURE); /* Error must've occurred in order for a different value to be present */
}
}
}
}
union _io {
int i;
double d;
};
void get_inputs_integer (int *a, int *b) {
printf("Enter first term: ");
scanf("%i", a);
printf("Enter second term: ");
scanf("%i", b);
}
void get_inputs_double (double *a, double *b) {
printf("Enter first term: ");
scanf("%lf", a);
printf("Enter second term: ");
scanf("%lf", b);
}
int main (int argc, char **argv) {
union _io operand1, operand2, result;
operation_mode o_mode;
data_mode d_mode = INTEGER_MODE;
printf("This program implements a calculator.");
do {
o_mode = ask_mode();
if (o_mode == TOGGLE) {
if (d_mode == INTEGER_MODE) {
d_mode = DOUBLE_MODE;
printf("Calculator now on double mode\n");
} else {
d_mode = INTEGER_MODE;
printf("Calculator now on integer mode\n");
}
} else if (o_mode != EXIT) {
if (d_mode == INTEGER_MODE) {
get_inputs_integer(&operand1.i, &operand2.i);
switch (o_mode) {
case ADDITION:
result.i = operand1.i + operand2.i;
break;
case SUBSTRACTION:
result.i = operand1.i - operand2.i;
break;
case MULTIPLICATION:
result.i = operand1.i * operand2.i;
break;
case DIVISION:
result.i = operand1.i / operand2.i;
break;
default:
exit(EXIT_FAILURE); /* Error must've occurred in order for a different value to be present */
}
printf("The result is %i\n", result.i);
} else {
get_inputs_double(&operand1.d, &operand2.d);
switch (o_mode) {
case ADDITION:
result.d = operand1.d + operand2.d;
break;
case SUBSTRACTION:
result.d = operand1.d - operand2.d;
break;
case MULTIPLICATION:
result.d = operand1.d * operand2.d;
break;
case DIVISION:
result.d = operand1.d / operand2.d;
break;
default:
exit(EXIT_FAILURE); /* Error must've occurred in order for a different value to be present */
}
printf("The result is %lf\n", result.d);
}
}
} while (o_mode != EXIT);
}
I need to write a program that requests two floating-point numbers and prints the value of
their difference divided by their product, and to have the program loop through pairs of
input values until the user enters nonnumeric input. I need to use scanf to take the input.
So, as I know that scanf return a value 0 or 1 for true/false so I though testing it to accomplish the last part of the question, but I'm trying to figure out how to make sure the loop goes back to ask for input.
My code is:
int main()
{
double num1, num2, different, product, answer;
printf("please enter 2 floatig point numbers:\n");
printf("number one is?\n");
while (scanf("%lf", &num1) ==1)
{
printf("number two is?\n");
while (scanf("%lf", &num2) ==1)
{
if (num1 > num2)
{
different = num1 - num2;
}
if (num2 > num1)
{
different = num2 - num1;
}
if (num1 == num2)
{
different = 0;
}
product = num1*num2;
answer = different/product;
printf("%lf", answer);
}
printf("you're out!");
}
printf("you're out!");
}
Example input:
first num 4.5
second num 3.5
output:
please enter 2 floatig point numbers:
number one is?
4.5
number two is?
3.5
0.063492
I'm getting the right answer and the program keeps running but I'm looking for a solution to go back for the input request.
You should first note that whatever made your scanf fail the first time, will probably make it fail the second time. So a loop such as this:
while (scanf("%lf", &a) != 1);
could become an infinite loop.
Also, when reading two or more values at the same time, it would be hard to track what is read and what is not. Therefore, I advise reading the values one by one, in a form like this:
void clear_line()
{
char c;
while (scanf("%c", &c) == 1)
if (c == '\n')
return;
}
double read_value(const char *message)
{
double d;
while (1)
{
printf("%s", message);
if (scanf("%lf", &d) == 1)
return d;
if (feof(stdin))
{
printf("Unexpected end of file\n");
return 0;
}
printf("Invalid input\n");
clear_line();
}
}
...
num1 = read_value("Enter first number: ");
num2 = read_value("Enter second number: ");
if (feof(stdin))
/* handle error */
What this basically does is try reading the value until the user produces a correct one. In case of incorrect input, one line of input is consumed and thrown away so the left over of whatever the user has input would not affect the next scanf and create a chain of errors.
Its just simply a pattern to define the number of input are you wanting. the simpler version of your code is
while( scanf("%d %d", &a,&b) == 2 )
//
here scanf return the 2 as a return value.
so you are checking while(2 == 2), make the number of input are you wanting
while( scanf("%lf %lf", &num1,&numb2) == 2 )
{
if (num1 > num2)
{
different = num1 - num2;
}
if (num2 > num1)
{
different = num2 - num1;
}
if (num1 == num2)
{
different = 0;
}
product = num1*num2;
}
You can simply do it like:
while(1)
{
printf("number one is?\n");
if(scanf("%lf", &num1) != 1)
{
break;
}
printf("number teo is?\n");
if(scanf("%lf", &num2) != 1)
{
break;
}
if (num1 > num2)
{
different = num1 - num2;
}
if (num2 > num1)
{
different = num2 - num1;
}
if (num1 == num2)
{
different = 0;
}
product = num1*num2;
answer = different/product;
printf("%lf", answer);
}
}