Intro to C: Addition and Printing - c

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) );
}

Related

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

How do I keep my program asking me info until I tell him to stop?

Im making a calculator with A LOT of functions, Im not nearly done with the functions. But I thought, I want the program active after returning me the value I asked for. My logic was to put it into a while loop, but clearly my idea and how I put it are not equal. Or maybe my logic doesnt work in this case. Anyway, imagine I ask the program how much its 2+2 and it returns me 4. Done, but I want it to ask me again for another operation, how can I do that?
Im really new with this stuff, so thanks for the help.
To resume the code below. I ask for a value, then scan it, then ask for a operator, then I ask wether if the user want to continue or not, if he says yes thats the condition for the loop ---> while(condition != 'yes' );{
And if not, just end the program. And I putted the operations inside the loop.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int input;
double sinus;
int op;
printf(" What function do you want to use? \n \n --------------------------------------- \n");
printf(" BASIC OPERATIONS --> type 1 \n --------------------------------------- \n");
printf(" TRIGONOMETRIC FUNCTIONS \n sin --> type 2 \n cos --> type 3 \n tan --> type 4 \n arcsin --> type 5 \n arccos --> type 6 \n arctan --> type 7 \n --------------------------------------- \n");
scanf("%d", &op);
char condition[5];
printf("Stop? Type: yes or no");
scanf("%s", &condition);
while(condition != 'yes' );{
if (op == 1) {
double val1;
char op1;
double val2;
printf("Please type a number: \n" );
scanf("%lf", &val1);
printf("Please type an operator: \n" );
scanf(" %c", &op1);
printf("Please type another number: \n" );
scanf("%lf", &val2);
if (op1 == '+') {
printf("%f \n", val1 + val2);
}
if (op1 == '-') {
printf("%f \n", val1 - val2);
}
if (op1 == '*') {
printf("%f \n", val1 * val2);
}
if (op1 == '/') {
printf("%f \n", val1 / val2);
}
}
else if (op == 2) {
double arg;
printf("Please type the argument of sin(x) \n");
scanf("%lf", &arg);
printf("The value is %f", sin(arg));
}
else if (op == 3) {
double arg;
printf("Please type the argument of cos(x) \n");
scanf("%lf", &arg);
printf("The value is %f", cos(arg));
}
else if (op == 4) {
double arg;
printf("Please type the argument of tan(x) \n");
scanf("%lf", &arg);
printf("The value is %f", tan(arg));
}
else if (op == 5) {
double arg;
printf("Please type the argument of arcsin(x) \n");
scanf("%lf", &arg);
printf("The value is %f", asin(arg));
}
else if (op == 6) {
double arg;
printf("Please type the argument of arccos(x) \n");
scanf("%lf", &arg);
printf("The value is %f", acos(arg));
}
else if (op == 7) {
double arg;
printf("Please type the argument of arctan(x) \n");
scanf("%lf", &arg);
printf("The value is %f", atan(arg));
}
else {
printf("%d", 0);
}
}
}
Sorry for too many to read:((( Im not experienced with forums.
The following example will give you an idea how things can be repeated based on input.
check how strcmp is done,that way you are doing is wrong.
Also consider using switch for handling multiple cases of input and their operations.
#include<stdio.h>
#include <string.h>
#include <ctype.h> // isspace
int main() {
char choice[] = "Yes";
do{
int i = 0;
/**
* implement all you want here
*/
printf("Enter Yes to repeat, to exit enter any other non blank string\n");
while(isspace(choice[i] = getchar()));
while((choice[++i] = getchar()) != '\n');
choice[i] = '\0';
printf("choice = %s, i = %d\n", choice, i);
}while(!strcmp(choice,"Yes") );
return 0;
}

Multiple different type inputs in one line

I'm trying to make a binary calculator that terminates the the program when q is entered. As a result I made a variable called quit to act as the flag q is entered. However when I made the scanf for the variable q it seems to take away split the inputs up when q is not pressed. for example, if I enter 110 + 110 I get:
110 + 110 = 1000
as if it's doing 10 + 110.
The input has to be all in one line. The format of the input is always going to be:
Operand operator Operand
Which is why I have the:
scanf(" %s %c %s",Binary1, &op, Binary2);
on my code. However if the user input is just q or Q it terminates the program.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
double convertDouble(char Bin []);
double convertBinary(double theAns);
double calculate(double num1,double num2,char op);
main(void) {
char op;
float num1,num2;
char quit;
double n1,n2,ans;
double binAns;
char Binary1[20];
char Binary2[20];
char Input[100];
char myChar;
int i = 0;
// quit = 'k';
while (quit != 'q'){
printf("Enter an expression using binary numbers or Q to quit: ");
// scanf("%s", &quit);
if(quit == 'q' ){
exit(EXIT_SUCCESS);
}else{
}
scanf(" %s %c %s",Binary1, &op, Binary2);
/* while(Binary1[i] > 49 || Binary2[i] > 49){
if(Binary1[i] >= 'q' || Binary1[i]<= 'Q' ){
exit(0);
quit = 'q';
}else{
printf("please enter binary: ");
scanf("%s %c %s\n",&Binary1, &op, &Binary2);
}
i++;
} */
// quit[0] = Binary1[0];
printf("quit = %c\n", quit);
printf("Binary1 =%s\n", Binary1);
printf("op =%c\n", op);
printf("Binary2 =%s\n", Binary2);
n1 = convertDouble(Binary1);
n2 = convertDouble(Binary2);
ans = calculate(n1,n2,op);
binAns = convertBinary(ans);
// printf("value of n1 = %f\n", n1);
// printf("value of n2 = %f\n", n2);
// printf("value of binAns = %f\n", binAns);
// printf("ans = %f", ans);
printf(" = %f\n",binAns);
} // end of while
printf("quit = %c\n", quit);
printf("Binary1 =%s\n", Binary1);
printf("op =%c\n", op);
printf("Binary2 =%s\n", Binary2);
printf("quit");
exit(EXIT_SUCCESS);
}
Note:
More info about my program: the reason why I have the input binaries as strings was because it needs to convert them to a double. It does this in a different function called convertDouble which is not pasted here. It calculates the answer in the function calculate(also not pasted). The answer is converted to a binary in the convertBinary function and then is displayed.
Example of How it's supposed to run
Enter an expression using binary numbers or Q to quit: 1101.001 * 101.1101
= 1001100.0100101
Enter an expression using binary numbers or Q to quit: 0.0000000001 * 0.0000000001
= 0.00000000000000000001
Enter an expression using binary numbers or Q to quit: 0.111 * 1000.0
= 111.0
Enter an expression using binary numbers or Q to quit: 11.0 * 11.0
= 1001.0
Enter an expression using binary numbers or Q to quit: 11.11 + 11.11
= 111.1
Enter an expression using binary numbers or Q to quit: 101.1 / 10.0
= 10.11
Enter an expression using binary numbers or Q to quit: 1001.11 - 11.01
= 110.1
Enter an expression using binary numbers or Q to quit: q
Keep code as simple as possible, keep the minimum number of variables and functions required for functionality.
Think carefully about each requirement of the program, treat them as individual small problems ...
Like this ...
#include <stdio.h>
#include <stdlib.h>
#define BUFLEN 32
double convertToDouble(const char *chars) {
return strtod(chars, NULL);
}
double calculateAnswer(double left, char operator, double right) {
switch (operator) {
case '<': return left < right; break;
case '>': return left > right; break;
case '=': return left == right; break;
case '*': return left * right; break;
case '/': return left / right; break;
}
/* do something */
return -1;
}
int main(int argc, char *argv[]) {
char buffer[BUFLEN*2];
printf("Enter an expression using binary numbers or Q to quit: ");
while (fgets(buffer, BUFLEN, stdin)) {
char left[BUFLEN] = {0},
right[BUFLEN] = {0},
operator = 0;
if(sscanf(buffer, "%s %c %s\n", left, &operator, right)) {
if (!operator) {
if (left[0] == 'q' || left[0] == 'Q') {
printf("Bye!\n");
break;
}
}
printf("%s %c %s = %f\n",
left, operator, right,
calculateAnswer(
convertToDouble(left),
operator,
convertToDouble(right)));
} else {
/* do something */
}
printf("Enter an expression using binary numbers or Q to quit: ");
}
return 0;
}
Note that, this code is not meant to be correct, it's an approximation of the requirements you describe without putting in too much effort.
Much more importantly, it's easy to understand.
Ctrl+C is standard way to terminate console program. But if you want to use 'q' as terminate signal, you can do the following:
char line[128];
float a, b;
char op;
while(true) {
printf("Enter an expression using binary numbers or q to quit: ");
if( gets(line) ) {
if( strcmp(line, "q") == 0 || strcmp(line, "Q") == 0 ) {
printf("See you later");
break;
}
if( sscanf(line, "%f %c %f", &a, &op, &b) != 3 ) {
printf("Error: wrong expression. Please try again");
continue;
}
...
}
}
You can read line of text (function getline or gets_s) and parse it (function sscanf). Try something like this:
char buffer[128];
int nbParsedItems;
printf("Enter an expression using binary numbers or Q to quit: ");
gets_s(buffer, 127);
if (buffer[0] == 'q' || buffer[0] == 'Q')
return;
nbParsedItems = sscanf(buffer, " %s %c %s", Binary1, &op, Binary2);
if (nbParsedItems == 3) /* in other cases you should ask user to enter request again */
{
/* calculate */
}

calculator output in c

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.

Simple calculator program in C

I need to write a simple program in C that makes simple calculations of: +,-,*,/
Now, I am using Visual Studio Express 2013, and here is the code:
#include <stdio.h>
#include <stdlib.h>
int main(){
double a, b;
double sum = 0;
char o; //operator
printf("Enter operator\n");
scanf_s("%c", &o);
printf("Enter first operand\n");
scanf_s("%f", &a);
printf("Enter second operand\n");
scanf_s("%f", &b);
if (o == '+'){
sum = a + b;
printf("The result is", &sum);
}
if (o == '-'){
sum = a - b;
printf("The result is", sum);
}
if (o == '*'){
sum = a*b;
printf("The result is", sum);
}
if (o == '/'){
if (b == !0){
sum = a / b;
printf("The result is", sum);
}
else printf("Error");
}
getchar();
}
My output: Enter operator
+
Enter first operand
3.5
Enter second operand
5.4
And after I type the second number- the program exits, and nothing!
There are no compilation errors, and I have no idea what to do. Can someone help, please?
You're not using printf correctly. This is what you're using.
printf("The result is", &sum);
You're not specifying the type of output in the format string, and you're passing the address of the variable you want to print, not the value.
You should use:
printf("The result is %lf\n", sum);
%lf is specifying that you want to print a double, \n adds a newline, and you pass the value of the variable sum, not it's address.
Also, you should change if (b == !0){ to if (b != 0){. If you leave what you put, it's the equivalent to if (b == 1){, which probably isn't what you want.
EDIT Here is the code, with my modifications, which gives correct results. I'll indicate which lines I changed
#include <stdio.h>
#include <stdlib.h>
int main(){
double a, b;
double sum = 0;
char o; //operator
/* I had to use scanf, since I'm not using MS/Visual Studio, but GCC */
printf("Enter operator\n");
scanf("%c", &o);
printf("Enter first operand\n");
scanf("%lf", &a); /* changed %f to %lf */
printf("Enter second operand\n");
scanf("%lf", &b); /* changed %f to %lf */
/* I prefer to use if ... else if ..., this is personal preference */
if (o == '+'){
sum = a + b;
printf("The result is %lf\n", sum); /* Changed, see original post */
} else if (o == '-'){
sum = a - b;
printf("The result is %lf\n", sum); /* Changed, see original post */
} else if (o == '*'){
sum = a*b;
printf("The result is %lf\n", sum); /* Changed, see original post */
} else if (o == '/'){
if (b != 0){
sum = a / b;
printf("The result is %lf\n", sum); /* Changed, see original post */
}
else printf("Error");
}
getchar();
return 0;
}
You are using %f format to read doubles. You should use %lf:
scanf_s("%lf", &a);
The print methods actually don't print the result (format is incomplete). And, instead of the value, you are passing variable's address. It should be:
printf("The result is %e", sum);
You should also change if (b == !0) to if (b != 0)
Now it's working fine I made some changes to it
the problem was with ur "scanf_s" and "%f" go throw with it
#include<stdio.h>
#include<stdlib.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("%d", &a);
printf("Enter second operand\n");
scanf("%d", &b);
if (o == '+'){
sum = a + b;
printf(" The result is %d", sum);
}
if (o == '-'){
sum = a - b;
printf("The result is %d", sum);
}
if (o == '*'){
sum = a*b;
printf("The result is %d", sum);
}
if (o == '/'){
if (b == !0){
sum = a / b;
printf("The result is %d", sum);
}
else printf("Error");
}
getchar();
}

Resources