I have a problem with calculator. I want to program a calculator, but it "works" with letters too. If I enter f.e letters "s" and "u", i get answer 0. How to repair that?
# include <stdio.h>
int main() {
char operator;
int a,b;
printf("Enter the operator (+, -, *, /): ");
scanf("%c", &operator);
printf("Enter two number and seperate them with space: ");
scanf("%lf %lf",&a, &b);
switch(operator)
{
case '+':
printf("%.2lf + %.2lf = %.2lf",a, b, a + b);
break;
case '-':
printf("% 2lf - %.2lf = % 2lf",a, b, a - b);
break;
case '*':
printf("%.2lf * %.2lf = %.2lf",a, b, a * b);
break;
case '/':
printf("%.2lf / %.2lf = %.2lf",a, b, a / b);
break;
default:
printf("Error!");
}
return 0;
}
Sorry, if the question has been up here.
The link to answer is also appreciated!
Cheers!
I have made the corrections discussed in comments
#include <stdio.h>
int main(void) { // correct definition
char operator;
double a,b; // correct type
printf("Enter the operator (+, -, *, /): ");
if(scanf("%c", &operator) != 1) { // add error check
puts("Bad operator entered");
return 1;
}
printf("Enter two number and seperate them with space: ");
if(scanf("%lf %lf",&a, &b) != 2) { // add error check
puts("Bad value(s) entered");
return 1;
}
switch(operator)
{
case '+':
printf("%.2lf + %.2lf = %.2lf",a, b, a + b);
break;
case '-':
printf("%.2lf - %.2lf = % 2lf",a, b, a - b); // corrected typo
break;
case '*':
printf("%.2lf * %.2lf = %.2lf",a, b, a * b);
break;
case '/':
printf("%.2lf / %.2lf = %.2lf",a, b, a / b);
break;
default:
printf("Error!");
}
return 0;
}
UPDATED:
i found my Ooldest code in library Folder maybe it helps you in that problem. This will definitely Work.
char operator;
printf("Enter the Operation in ( * , / , - , + )");
scanf("%s",&operator);
if(operator!='+' || operator!='-' || operator!='*' || operator!='/')
{
return 0;
}
I got it working. It was easier to do than I thought.
So the right code, I'll put comment to answer.
#include
int main(void) { // correct definition
char operator;
double a,b; // correct type
printf("Enter the operator (+, -, *, /): ");
if(scanf("%c", &operator) != 1) { // add error check
puts("Bad operator entered");
return 1;
}
printf("Enter two number and seperate them with space: ");
if(scanf("%lf %lf",&a, &b) != 2) { // add error check
puts("Bad value(s) entered");
return 1;
}
switch(operator)
{
case '+':
printf("%.2lf + %.2lf = %.2lf",a, b, a + b);
break;
case '-':
printf("%.2lf - %.2lf = % 2lf",a, b, a - b); // corrected typo
break;
case '*':
printf("%.2lf * %.2lf = %.2lf",a, b, a * b);
break;
case '/':
if(b!=0){ //added an if-sentence
printf("%.2lf / %.2lf = %.2lf\n",a, b,
a / b);
}
else
printf("Can't divide by zero\n");
break;
default:
printf("Error!");
}
return 0;
}
Basically, I just put an if-sentence to case('/').
Related
When I started writing my program (I didn't add system(cls); at that time), it started the console as soon as I doubled clicked on the exe file. But when I added the system(cls); it took 4-5 seconds to open. Why? Is there any way to fix this?
My Code (it's a simple calculator) -
#include <stdio.h> // for printf() and scanf()
#include <stdlib.h> //for exit() and system()
#include <windows.h> // for SetConsoleTitle()
#include <math.h> // for sqrt()
int calculation();
int main()
{
int afterCal;
SetConsoleTitle("My Calculator");
printf("Welcome to my Calculator\n");
calculation();
for(;;)
{
printf("\nAnother Calculation? type 1\n");
printf("Quit? type 0\n");
scanf( "%d", &afterCal);
if (afterCal == 1)
{
system("cls");
calculation();
}
else if (afterCal == 0)
{
exit(0);
}
else
{
system("cls");
printf("\nError, enter 0 or 1\n");
}
}
return 0;
}
int calculation()
{
double num1, num2;
char ope, square = 251;
printf("Enter number 1 -\n");
scanf("%lf", &num1);
printf("Enter number 2 (put 0 if you want square/cube root or cube) -\n");
scanf("%lf", &num2);
if (num2 == 0)
{
printf("Enter operation - s for square root, r for cube root, c for cube\n");
}
else
{
printf("Enter operation - +, -, *, /\n");
}
scanf(" %c", &ope);
switch (ope)
{
case '+':
system("cls");
printf("%g + %g = %g\n", num1, num2, num1 + num2);
break;
case '-':
system("cls");
printf("%g - %g = %g\n", num1, num2, num1 - num2);
break;
case '*':
system("cls");
printf("%g * %g = %g\n", num1, num2, num1 * num2);
break;
case '/':
system("cls");
printf("%g / %g = %g\n", num1, num2, num1 / num2);
break;
case 's':
system("cls");
printf("%c%g = %g\n", square, num1, sqrt(num1));
break;
case 'r':
system("cls");
printf("Cube root of %g = %g\n", num1, cbrtf(num1));
break;
case 'c':
system("cls");
printf("Cube of %g = %g\n", num1, num1 * num1 * num1);
break;
default:
system("cls");
printf("Error, invalid operation %c\n", ope);
break;
}
return 0;
}
Any help would be appreciated!
1st I was using the MinGW x64 compiler (at that time the startup delay occurred), but now I am using Visual Studio 2022 ide and its compiler, and my exe opens instantly! Problem Solved!
But I am still confused, why did MinGW give that much startup delay...
I wanna restrict symbols that is typed or else print error and go back to menu. It means that if i type $ it happens an error and it goes back to operators menu, how to do this?
#include <stdio.h>
#include<windows.h>
int main()
{
char op;
int a, b =0;
int res =0;
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),BACKGROUND_GREEN|BACKGROUND_INTENSITY);
printf("\n\nBASIC CALCULATOR!");
x:
printf ("\nType the operator: +, -, * or /\n");}
scanf("%c", &op);
if (op == '+' || op == '-' || op == '*' || op == '/')
{
printf ("\nType 2 numbers:\n");
scanf("%d%d", &a, &b);
}
else {
printf ("...\n");
}
switch (op){
case '+':
res = a + b;
printf ("...\n\n");
printf ("Result = %d\n", res);
break;
case '-':
res = a - b;
printf ("...\n");
printf ("Result = %d\n", res);
break;
case '*':
res = a * b;
printf ("...\n");
printf ("Result = %d\n", res);
break;
case '/':
res = a / b;
printf ("...\n");
printf ("Result = %d\n", res);
break;
default:
printf ("\n\n...");
}
fflush(stdin);
goto x;
return (0);
}
updateddd
I don't have that much knowledge about libraries, i tried simple functions
I am trying to program a simple calculator. Here is my code first:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char operator = 0;
float num1 = 0.0;
float num2 = 0.0;
float sol = 0.0;
while (operator != 'q') {
printf("Operator: ");
scanf("%c", &operator);
printf("First Number: ");
scanf("%f", &num1);
printf("Second Number: ");
scanf("%f", &num2);
switch (operator)
{
case '+': sol = num1 + num2; break;
case '-': sol = num1 - num2; break;
case '*': sol = num1 * num2; break;
case '/': sol = num1 / num2; break;
case 'q': printf("Finished!"); exit(0);
default: printf("Error!"); exit(0);
}
printf("The solution is: %.2f\n\n", sol);
}
return 0;
}
So for me the code is fine. As you can see I did this with a while loop that lets you calculate until you type in 'q' as operator. The first run of the loop works fine but then it gets creepy (my console):
Operator: +
First Number: 5
Second Number: 4
The solution is: 9.00
Operator: First Number:
Why does the program not let me enter an operator in the second loop run?
Most format specifiers with scanf will skip leading whitespace. %c does not.
scanf("%f", &num2); at the end of the first iteration leaves a newline in the input buffer.
scanf("%c", &operator); at the start of the second iteration, reads the newline and proceeds.
using a space before %c in scanf(" %c", &operator); will allow %c to skip the leading whitespace and capture the operator.
You should check scanf for errors:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char operator = 0;
float num1 = 0.0;
float num2 = 0.0;
float sol = 0.0;
while (operator != 'q') {
printf("Operator: ");
if((scanf(" %c", &operator)) != 1){
printf("Error, Fix it!\n");
exit(1);
}
printf("First Number: ");
if((scanf("%f", &num1)) != 1){
printf("Error, Fix it!\n");
exit(1);
}
printf("Second Number: ");
if((scanf("%f", &num2)) != 1){
printf("Error, Fix it!\n");
exit(1);
}
switch (operator){
case '+': sol = num1 + num2; break;
case '-': sol = num1 - num2; break;
case '*': sol = num1 * num2; break;
case '/': sol = num1 / num2; break;
case 'q': printf("Finished!"); exit(0);
default: printf("Error!"); exit(0);
}
printf("The solution is: %.2f\n\n", sol);
}
return 0;
}
and as you can see I changed scanf("%c", &operator); to this scanf(" %c", &operator); to make scanf to ignore (skip) Whitespace.
i m new in programing.
i've written a simple program.
i want to repeat the program again and again and it can only exit when user wants to exit.
here is my program
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
int num1, num2, a, m, s, choice;
float d;
printf("\nEnter The First Number: ");
scanf("%d", &num1);
printf("\nEnter The Second Number: ");
scanf("%d", &num2);
a=num1+num2;
m=num1*num2;
s=num1-num2;
d=(float)(num1/num2);
printf("\nEnter Your Choice \nFor Addition Type A \nFor Multipication Type M \nFor Division Type D \nFor Substraction Type S : ");
scanf(" %c", &ch);
switch(ch)
{
case 'A': printf("\nThe Addition Of The Number Is= %d", a);
break;
case 'M': printf("\nThe Multipication Of The Numbers Is= %d", m);
break;
case 'S': printf("\nThe Substraction Of THe Numbers Is= %d", s);
break;
case 'D': printf("\nThe Division Of The Two Numbers Is= %f", d);
break;
default : printf("\nInvalid Entry");
break;
}
printf("\nPress Any Key To Exit");
getch();
return 0;
}
and here is the output
"Enter The First Number: 10
Enter The Second Number: 10
Enter Your Choice
For Addition Type A
For Multipication Type M
For Division Type D
For Substraction Type S : A
The Addition Of The Number Is= 20
Press Any Key To Exit"
I want a line before the line Press Any Key To Exit
"If You Want To Calculate Again Press Y
or
Press Any Key To Exit"
when press Y then the program should start from the beginning.
How can i do this???
wrap the code inside a do{} while() ?
char answer;
do{
printf("\nEnter The First Number: ");
scanf("%d", &num1);
printf("\nEnter The Second Number: ");
scanf("%d", &num2);
a=num1+num2;
m=num1*num2;
s=num1-num2;
d=(float)(num1/num2);
printf("\nEnter Your Choice \nFor Addition Type A \nFor Multipication Type M \nFor Division Type D \nFor Substraction Type S : ");
scanf(" %c", &ch);
switch(ch)
{
case 'A': printf("\nThe Addition Of The Number Is= %d", a);
break;
case 'M': printf("\nThe Multipication Of The Numbers Is= %d", m);
break;
case 'S': printf("\nThe Substraction Of THe Numbers Is= %d", s);
break;
case 'D': printf("\nThe Division Of The Two Numbers Is= %f", d);
break;
default : printf("\nInvalid Entry");
break;
}
printf("\nPress Y to continue. Press any Key To Exit");
scanf(" %c",&answer); // dont forget type &
}
while(answer == 'y' || answer == 'Y');
Declare a variable, let's say answer, which will store the user answer when you ask for "Press Y to continue. Press any Key To Exit". Check to see what value has that variable. If is 'y' or 'Y', the loop will repeat. If the user pressed other key, the loop is over.
You can also use recursion, which is often used in more functional oriented programming languages.
Pseudo-code:
myfunction = do
...
b <- somethingtodo
...
if b
then myfunction
else return ()
Relative to Jens's solution, it would look like:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main (void)
{
char choice;
int num1, num2, cont;
printf("Enter the first number: ");
scanf("%d", &num1);
getchar ();
printf("Enter the second number: ");
scanf("%d", &num2);
getchar ();
printf("A - addition\n");
printf("S - subtraction\n");
printf("M - multiplication\n");
printf("D - division\n");
printf("[ASMD]? ");
choice = (char)toupper(getchar());
getchar ();
printf("\n");
switch(choice)
{
case 'A':
printf("%d + %d = %d", num1, num2, num1 + num2);
break;
case 'S':
printf("%d - %d = %d", num1, num2, num1 - num2);
break;
case 'M':
printf("%d * %d = %d", num1, num2, num1 * num2);
break;
case 'D':
if (num2 == 0)
fprintf(stderr, "The divisor can not be zero");
else
{
printf("%d / %d = %f", num1, num2, (double)num1 / num2);
}
break;
default :
fprintf(stderr, "Invalid entry");
break;
}
printf("\n");
for (;;)
{
printf("Continue [YN]? ");
cont = toupper(getchar());
getchar ();
if (cont == 'Y')
return main(); // the difference.
else if (cont == 'N')
return EXIT_SUCCESS;
}
}
I would move the calculation stuff in it's own function and then use while() in main.
I have tried to fix other problems as well (this solution only uses standard C functions).
#include <stdio.h> // puts, printf, fprintf, scanf, getchar, stderr, EOF
#include <stdlib.h> // exit, EXIT_SUCCESS, EXIT_FAILURE
#include <ctype.h> // toupper
char fail_on_eof (int c)
{
if (c == EOF)
exit (EXIT_FAILURE);
// In case of fail_on_eof (scanf (...)) the return value of this this
// function is not useful
// scanf () returns the number of chars read or EOF
// getchar () returns a char or EOF
return (char) c;
}
void skip_to_next_line (void)
{
char c;
do
{
c = fail_on_eof (getchar ());
} while (c != '\n');
}
char read_upcase_char_line (char* prompt)
{
char c;
printf ("%s ", prompt);
c = fail_on_eof (toupper (getchar ()));
skip_to_next_line ();
return c;
}
int read_num_line (char* prompt)
{
int num;
printf ("%s ", prompt);
fail_on_eof (scanf ("%d", &num));
skip_to_next_line ();
return num;
}
int calculate (void)
{
char choice;
int num1, num2, cont;
num1 = read_num_line ("Enter the first number:");
num2 = read_num_line ("Enter the second number:");
puts("A - addition");
puts("S - subtraction");
puts("M - multiplication");
puts("D - division");
choice = read_upcase_char_line ("[ASMD]?");
puts("");
switch(choice)
{
case 'A':
printf("%d + %d = %d", num1, num2, num1 + num2);
break;
case 'S':
printf("%d - %d = %d", num1, num2, num1 - num2);
break;
case 'M':
printf("%d * %d = %d", num1, num2, num1 * num2);
break;
case 'D':
if (num2 == 0)
// Better use stderr for error messages
fprintf(stderr, "The divisor can not be zero");
else
{
printf("%d / %d = %f", num1, num2, (double)num1 / num2);
}
break;
default :
// Better use stderr for error messages
fprintf(stderr, "Invalid entry");
break;
}
printf("\n");
for (;;)
{
cont = read_upcase_char_line ("Continue [YN]?");
if (cont == 'Y')
return -1;
else if (cont == 'N')
return 0;
}
}
int main(void)
{
while (calculate ());
return EXIT_SUCCESS; // Use this constant to avoid platform specific issues with the return code
}
I made a simple calculator program using switch case, but the output is different than I expected.
int main(){
double a, b;
double sum = 0;
char o; //operator
printf("Enter operator\n");
scanf("%c", &o);
printf("Enter first operand\n");
scanf("%f", &a);
printf("Enter second operand\n");
scanf("%f", &b);
switch (o)
{
case '+':
sum = a + b;
break;
case '-':
sum = a - b;
break;
case '*':
sum = a * b;
break;
case '/':
sum = a / b;
break;
if (b == 0){ printf("Error"); }
break;
}
printf("The result is\n%10.10lf\n", sum);
getchar();
getchar();
}
The result of 'sum' is some huge astronomical numbers. Can someone tell why?
Try %lf instead of %f because that way you will have a and b as the type double rather than float.
a and b are both of type double. The correct format specifier for double in scanf is %lf, not %f (which is for float).
scanf("%lf", &a);
Note that in printf, %f is used or for double (the same for float because it's promoted to double). Since C99, %lf in printf is the same as %f.
you are trying to convert double to float which is not implicitly possible inside scanf or printf function. What scanf was doing, It was purging/reformatting the whole (double)input into an empty float value. Here is working one :
#include<stdio.h>
int main(){
double a, b;
double sum = 0;
char o; //operator
printf("Enter operator\n");
scanf("%c", &o);
printf("Enter first operand\n");
scanf("%lf", &a);
printf("Enter second operand\n");
scanf("%lf", &b);
switch (o)
{
case '+':
sum = a + b;
break;
case '-':
sum = a - b;
break;
case '*':
sum = a * b;
break;
case '/':
sum = a / b;
break;
if (b == 0){ printf("Error"); }
break;
}
printf("The result is\n %f\n", sum);
}
As everyone has pointed out, you need scanf ("%lf", &a); and same for b.
Now in your switch statement you wanted to prevent division by zero :
case '/':
sum = a / b;
break;
if (b == 0){ printf("Error"); }
break;
But what happens there is that you break; before getting to the condition. Suppose we removed that first break; the division by zero is still performed before you print the error message anyway.
One way to prevent division by zero would be :
case '/':
if (b)
sum = a / b;
else
printf("Error");
break;
where we check that b != 0 before we make the division and then we either divide or print the error message.