Basic calculator written in C only adds - c

I tried to make a basic calculator but whenever I make my inputs it adds rather than listening to my operator input.
I know that my if and if else statements aren't working but I don't really understand why. When I compile there are no errors and every other way that I've tried has resulted in many errors.
Here's the code:
#include <stdio.h>
int main(void) {
double num1;
double num2;
double x;
double operator;
printf("First number:\n");
scanf("%lf\n", &num1);
printf("Second number:\n");
scanf("%lf\n", &num2);
printf("Select operator:\n Division\n Multiplication\n Subtraction\n Addition\n");
scanf("%lf\n", &operator);
if (operator == '/' ) {
x=num1/num2;
}
else if (operator == '*') {
x=num1*num2;
}
else if (operator == '-') {
x=num1 - num2;
}
else {
x=num1 + num2;
}
printf("Result: %lf\n", x);
return 0;
}
Cheers!

Firstly, I'd avoid calling your variable 'operator' (it's a keyword in C++).
This is your variable:
double operator;
And here you read it as a double precision floating point number:
scanf("%lf\n", &operator);
And now you hope to treat it as a char:
if(operator == '-')
To fix this, change the type of operator to char:
char operator;
and read it as a char:
scanf("%c\n", &operator);

the posted code always results in addition because none of the comparisons ( '/', '-', '*' ) will ever compare equal to a double

Related

When I add two integers it says invalid although supposedly it's for characters and symbols. Am I missing something?

In my calculator I tried firstly to make one operation functioning to have integers be displayed properly and when someone inputted a character it would say invalid.
When I input two integers it say's invalid. Not the actual sum of it.
#include <stdio.h>
#include <conio.h>
int main(){
char op;
int num1, num2;
int result;
printf("Enter (+, -, /, *): ");
scanf("%c", &op);
printf("Enter Two Integers: \n");
scanf("%d %d", &num1, &num2);
switch (op){
case '+':
result = num1+num2;
if(!(num1 == '+' && num2 == '+')){
printf("Invalid");
}
else{
printf("Sum: %d ", result);
}
break;
case '-':
result = num1-num2;
printf("Difference: %d ", result);
break;
case '/':
result = num1/num2;
printf("Quotient: %d ", result);
break;
case '*':
result = num1*num2;
printf("Product: %d ", result);
break;
default:
break;
}
getch();
return 0;
}
I expected that with that new line of condition it will make characters and symbols print "Invalid"
if(!(num1 == '+' && num2 == '+'))
This doesn't make any sense for several reasons. First of all De Morgan's laws and boolean algebra is often considered a prerequisite before studying any form of programming. By applying De Morgan/common sense, then we can tell that the opposite to "if num1 is + and num2 is +" is "if num1 isn't + OR num2 isn't +". That is:
if(num1 != '+' || num2 != '+') or if you will if(!(num1 == '+' || num2 == '+')).
With that logic flaw out of the way, this is the wrong solution to the the actual problem anyway. You simply want to prevent the user from entering a character - any character not just '+' - when expecting a number. The easiest way of doing that is to check the result of scanf - it returns a number corresponding to the number of arguments successfully read. For example:
int result;
do
{
result = scanf("%d %d", &num1, &num2);
if(result != 2)
{
printf("You must enter two numbers!\n");
}
}
while(result != 2);
Another option is to read the input as a string with fgets and then parse that string afterwards.
As a side note, please note that <conio.h> has been obsolete for well over 20 years and if someone taught you to use it, you need a more updated source of learning. The future for freshly graduated MS DOS programmers isn't very promising...
Be sure to check the return value of scanf to ensure it read the number of values you expected.
num1 and num2 are int variables and you are reading into them using the %d specifier. If you type in + or other symbols, scanf("%d %d", &num1, &num2) will return 0. A simple demonstration:
$ cat > testing.c
#include <stdio.h>
int main(void) {
int op;
int result = scanf("%d", &op);
printf("%d\n", result);
}
$ gcc testing.c
$ ./a.out
+
0
$ ./a.out
67
1
The odds that num1 and num2 uninitialized both contain the value '+' are not impossible but highly unlikely, so the most likely outcome is that "Invalid." is printed.
As noted in comments, 43 is the ASCII code for '+' so if these specific numbers are input, both num1 and num2 will test as equal to 43 and their sum (86) will be printed.

passing argument 1 and 2 of ‘strcmp’ makes pointer from integer without a cast [-Wint-conversion]

Hello so I've been working a little prgramme which is sort of a calculator (I'm a beginner) and well as you can see in the tittle at then end of the code, the two if strcmp doesn't work. And vscode is telling me (for the strcmp) Exception has occurred. Segmentation fault. But gcc is telling me what is in the tittle.
#include <stdio.h>
#include <string.h>
int main()
{
float num1;
float num2;
float anwser;
int rnum = 1;
int hi = 0;
char operator;
char ifyorn;
char y = 'y';
char n = 'n';
while (hi == 0)
{
printf("Enter operator +, -, /, x: ");
scanf(" %c", &operator);
printf("Enter num %d :", rnum++);
scanf("%f", &num1);
printf("Enter num %d :", rnum++);
scanf("%f", &num2);
switch (operator)
{
case '+':
anwser = num1 + num2;
printf("Do you want to continue y/n \n");
scanf(" %c", &ifyorn);
break;
case '-':
anwser = num1 - num2;
printf("Do you want to continue y/n \n");
scanf(" %c", &ifyorn);
break;
case 'x':
anwser = num1 * num2;
printf("Do you want to continue y/n \n");
scanf(" %c", &ifyorn);
break;
case '/':
anwser = num1 / num2;
printf("Do you want to continue y/n \n");
scanf(" %c", &ifyorn);
break;
default:
printf("This is not a valid character please try again :(");
break;
}
if(strcmp (ifyorn, n) == 0)
{
printf("%f", anwser);
hi == 1;
}
if(strcmp (ifyorn, y) == 0)
{
hi == 0;
}
}
}
The variables ifyorn, y and n are declared having the type char.
char ifyorn;
char y = 'y';
char n = 'n';
The function strcmp expects arguments of the pointer type char * that point to strings.
So these if statements
if(strcmp (ifyorn, n) == 0)
and
if(strcmp (ifyorn, y) == 0)
are incorrect. Instead you should write
if ( ifyorn == n )
and
if ( ifyorn == y )
Also instead of assignments you are using the comparison operator in these statements
hi == 1;
and
hi == 0;
You need to write
hi = 1;
and
hi = 0;
Increasing the variable rnum looks senseless
printf("Enter num %d :", rnum++);
scanf("%f", &num1);
printf("Enter num %d :", rnum++);
scanf("%f", &num2);
Why not just to write
printf("Enter num %d :", 1 );
scanf("%f", &num1);
printf("Enter num %d :", 2 );
scanf("%f", &num2);
And in the code snippet under the label default you should add one more statement
default:
printf("This is not a valid character please try again :(");
ifyorn = y;
break;
You don't have to be mean to the guy ,he is learning.
You are getting this error because you are passing characters to strcmp() instead of pointers to characters.
Here is more information regarding that function.
https://www.programiz.com/c-programming/library-function/string.h/strcmp

If statement is not working with char in C

I've been trying to make this if work I've tried to put scanf in every way possible and that was not the problem because it picks it up the "+" is stored as I see it on the printf below.
Can anyone figure out why not?
Thanks
float number1;
float number2;
float total;
char operator[1];
printf("Welcome to the calculator\n");
while(3>2)
{
printf("Pick a number\n");
scanf("%f", &number1);
printf("Que quieres hacer?\n");
scanf(" %c", &operator);
printf("You wrote %s\n", operator);
if(operator =='+')
{
printf("This works!");
}
}
This code snippet
scanf(" %c", &operator);
printf("You wrote %s\n", operator);
if(operator =='+')
{
printf("This works!");
}
is incorrect independent on how the variable operator is declared.
If the variable operator is declared like
char operator;
then this statement
printf("You wrote %s\n", operator);
invokes undefined behavior.
In this case you need to write
printf("You wrote %c\n", operator);
If the variable operator is declared as a character array as for example
char operator[N];
where N is some value then at least this statement
if(operator =='+')
does not make a sense and the condition will always evaluate to false.
Pay attention to that instead of this condition in the while loop
while(3>2)
it would be much simpler and readable just to write
while ( 1 )

how to choose an operator and show it

I don't know what is wrong wiht my program, i tried to enter the numbers from keyboard and enter any operator and sort them like "a+b", but I don't know if it is correct so far, I don't have errors, but when I enter an operator it shows "You did not enter an opperator" it goes straight to the else, I don't know why. If you could please help me, thank you!
int main()
{
int a, b;
int op;
int var = '+';
int var1= '-';
int var2= '/';
int var3= '*';
printf("Choose your 2 numbers: ");
scanf("%i", &a);
scanf("%i", &b);
printf("Choose your operator (+, -, *, /): ");
scanf("%i", &op);
if(op == var || op == var1 || op == var2 || op == var3)
{
printf("The correct order is: %i, %i, %i", a, op, b);
}
else
{
printf("You did not enter an operator");
}
return 0;
}
So, first of all it'd be better to declare your op variable as a char instead of int as you are trying to read a character from the keyboard and not an integer number. Indeed if your try to print out your op variable as it is in your code you'll find out that its value is 0.
After changing this you should also change all %i for that variable to %c. This though will give a problem when using scanf(), which is that it will look like it got skipped. This is because the scanf() will read the last \n from the user as the character and put it in your variable.
To fix this you just need to put a space before %c so that the scanf() will skip the first whitespace character and then read from the keyboard. You can find more detailed explanation about this here
Anyway down here there's the working code.
int main()
{
int a, b;
char op;
int var = '+';
int var1 = '-';
int var2 = '/';
int var3 = '*';
printf("Choose your 2 numbers: ");
scanf("%d", &a);
scanf("%d", &b);
printf("Choose your operator (+, -, *, /): ");
scanf(" %c", &op);
if(op == var || op == var1 || op == var2 || op == var3)
{
printf("The correct order is: %i, %c, %i", a, op, b);
}
else
{
printf("You did not enter an operator.");
}
return 0;
}

Intro to C: Addition and Printing

I'm trying to making a rudimentary calculator that can perform a variety of arithmetic functions, starting with addition! Right now I've got the basic logic of it worked out, but I'm not sure exactly how to take two inputs and print it out!
#include <stdio.h>
int main()
{
char mychar;
int a;
int op1;
int op2;
printf("Welcome to Andrew Hu's calculator program!\n"); //Greeting
while(1)
{ printf("Enter a mathematical operation to perform:\n");
scanf("%c", &mychar);
if(mychar == '+') //Valid Operators
a = 1;
else
a = 0;
if(a == 0) //Operator Checker, error if invalid
printf("\nError, not a valid operator\n");
else if(a == 1){
printf("%c\n", &mychar),
printf("Enter OP1:\n"),
/* not sure what to put here to echo the character as a decimal*/
printf("Enter OP2:\n"),
/* not sure what to put here to echo the character as a decimal either*/
printf("Result of %d %c %d = %d\n", op1, mychar, op2, (op1 + op2) )
/* this last line I'm not too sure of. I'm trying to print out the expression
which is op1 + op2 = the sum of both. */
;
}
}
use scanf statement to take the inputs,just the same way you have taken mathematical operators.A switch case statement would be good to implement the calculator.
scanf(" %d",&op1);
Use the scanf function to read in a floating-point value like
double op1 = 0.0;
scanf("%lf", &op1);
The %lf denotes to read the entered value as a float-value.
As you enter the values on the command-line they will be displayed.
else if(a == 1){
printf("%c\n", mychar), // don't use & with printf as it will print the address of mychar
printf("Enter OP1:\n"),
double op1 = 0.0;
scanf("%lf", &op1);
printf("Enter OP2:\n"),
double op2 = 0.0;
scanf("%lf", &op2);
if(a == 1)
printf("Result of %lf + %lf = %lf\n", op1, op2, (op1 + op2) );
}

Resources