I just wanna know how to save or store a symbol such as +, -, / and * so that i could use it in if-statements to perform whatever symbol the user inputs. I know that my code is wrong so any kind of help will be appreciated.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int int1, int2, sum;
char oper;
printf("Enter Value Here: ");
scanf("%d", &int1);
printf("Enter Operation Here: ");
scanf("%s", &oper);
printf("Enter Value Here: ");
scanf("%d", &int2);
if (oper == "+")
sum = int1 + int2;
printf("The sum is %d", sum);
return 0;
}
You could do something like this:
#include<stdio.h>
int main(void){
int int1, int2, sum=0;
char op;
printf("Please enter one of the following Operators [*] [/] [+] [-] ");
if((scanf("%c",&op)) != 1){
printf("Error\n");
}
printf("Enter Value Here: ");
if((scanf("%d", &int1)) != 1){
printf("Error\n");
}
printf("Enter Value Here: ");
if((scanf("%d", &int2)) != 1){
printf("Error\n");
}
if (op == '/'){
sum = int1 / int2;
}else if(op == '*'){
sum = int1 * int2;
}else if(op == '+'){
sum = int1 + int2;
}else if(op == '*'){
sum = int1 - int2;
}
printf("The sum is %d\n", sum);
return 0;
}
Edit:
For a better precision you can use float or double, Use double if you are not sure.
#include<stdio.h>
int main(void){
float int1, int2, sum=0;
char op;
printf("Please enter one of the following Operators [*] [/] [+] [-] ");
if((scanf("%c",&op)) != 1){
printf("Error\n");
}
printf("Enter Value Here: ");
if((scanf("%f", &int1)) != 1){
printf("Error\n");
}
printf("Enter Value Here: ");
if((scanf("%f", &int2)) != 1){
printf("Error\n");
}
if (op == '/'){
sum = int1 / int2;
}else if(op == '*'){
sum = int1 * int2;
}else if(op == '+'){
sum = int1 + int2;
}else if(op == '*'){
sum = int1 - int2;
}
printf("The sum is %.1f\n", sum);
return 0;
}
Most likely you are looking for a function pointers that will let you do some object oriented programming:
// type of functions being binary operations
typedef int (binary_operation*)(int, int);
// now you can define any binary operation on ints
int add_op(int a, int b) { // definition };
int mul_op(int a, int b) { // definition };
// main...
binary_operation f;
if (oper == "+")
f = add_op;
sum = f(in1,int2);
This way you can store your functions in container, you can pass them to other functions and so on.
why don't you use switch case in C:
char oper;
float num1,num2;
printf("Enter operator either + or - or * or / : ");
scanf("%c",&oper);
printf("Enter two operands: ");
scanf("%f%f",&num1,&num2);
switch(oper) {
case '+':
printf("%.1f + %.1f = %.1f",num1, num2, num1+num2);
break;
case '-':
printf("%.1f - %.1f = %.1f",num1, num2, num1-num2);
break;
case '*':
printf("%.1f * %.1f = %.1f",num1, num2, num1*num2);
break;
case '/':
printf("%.1f / %.1f = %.1f",num1, num2, num1/num2);
break;
default:
/* If operator is other than +, -, * or /, error message is shown */
printf("Error! operator is not correct");
break;
}
now using if-else:
//same code
scanf("%f%f",&num1,&num2);
if(oper=='+')
printf("%.1f + %.1f = %.1f",num1, num2, num1+num2);
else if(oper=='-')
printf("%.1f - %.1f = %.1f",num1, num2, num1-num2);
else if(oper=='*')
printf("%.1f * %.1f = %.1f",num1, num2, num1*num2);
else if(oper=='/')
printf("%.1f / %.1f = %.1f",num1, num2, num1/num2);
else
/* If operator is other than +, -, * or /, error message is shown */
printf("Error! operator is not correct");
Related
I'm building a calculator for my first project in C and everything worked fine until I implemented division. It keeps giving me the error "conflicting types for div", even though the function is exactly the same as all the others.
#include <stdio.h>
#include <stdlib.h>
int num1;
int num2;
char op;
int res;
int poscount;
int negcount;
int add(num1, num2) {
res = num1 + num2;
printf("Result: %d\n", res);
if(res >= 0)
poscount += 1;
else
negcount += 1;
return res;
}
int sub(num1, num2) {
res = num1 - num2;
printf("Result: %d\n", res);
if(res >= 0)
poscount += 1;
else
negcount += 1;
return res;
}
int mul(num1, num2){
res = num1 * num2;
printf("Result: %d\n", res);
if(res >= 0)
poscount += 1;
else
negcount += 1;
return res;
}
int div(num1, num2) {
res = num1 / num2;
printf("Result: %d\n", res)
return res;
}
int main() {
printf("Number: ");
scanf("%d", &num1); //Zahl 1
while(op != '=') {
printf("\nOperator: ");
scanf(" %c", &op); //Operator
if (op == '=') { //Überprüfung ob User weiterrechnen will
printf("Final result: %d\n", res);
printf("Number of positive: %d\n", poscount);
printf("Number of negatives: %d\n", negcount);
break;
}
printf("\nNumber: ");
scanf("%d", &num2); //Zahl
if(op == '+') {
num1 = add(num1, num2); //Addition
}
else if(op == '-'){
num1 = sub(num1, num2); //Subtraktion
}
else if(op == '*'){
num1 = mul(num1, num2); //Multiplikation
}
else if(op == '/'){ //Divisionen
if(num2 == 0) {
printf("Division by 0."); //Ausnahme Division durch 0
printf("No new result.");
}
else {
num1 = div(num1, num2);
}
else {
printf("Unknown operator");
}
}
return 0;
}
That's my code. Any ideas?
Your function div has the same name as the C standard library function div. The latter returns a value of the type div_t, and not an int, hence the error reporting "conflicting types".
The solution, and a good general practice, is to not have a function with the same name as one from the C standard library. Here, for example, name your function myDiv. I understand that this is an exercise in programming; otherwise you would want to use the standard library functions instead of reimplementing them.
Some additional advice:
Do not use global variables if their use can reasonably be avoided. This is the case here. In addition to that, do not reuse the variable names within functions (this is called shadowing).
Initialize poscount and negcount to 0.
Initialize op to some placeholder value (here, not =). Better yet, restructure the code so that op is assigned from the input first and evaluated afterwards.
Do not rely on the default type of variables being int, but declare the type explicitly.
The variable 'res' appears to be unused. Isn't the result stored in num1?
Use the pre-increment operator (++ before the variable name) instead of += 1.
Use a switch-statement instead of multiple else-if's.
Using English comments will make your code more easily understood by a wider audience.
Working code with some (not all) fixes applied:
#include <stdio.h>
#include <stdlib.h>
int poscount = 0;
int negcount = 0;
int add(int num1, int num2) {
int res = num1 + num2;
printf("Result: %d\n", res);
if (res >= 0)
++poscount;
else
++negcount;
return res;
}
int sub(int num1, int num2) {
int res = num1 - num2;
printf("Result: %d\n", res);
if (res >= 0)
++poscount;
else
++negcount;
return res;
}
int mul(int num1, int num2){
int res = num1 * num2;
printf("Result: %d\n", res);
if (res >= 0)
++poscount;
else
++negcount;
return res;
}
int myDiv(int num1, int num2) {
int res = num1 / num2;
printf("Result: %d\n", res);
return res;
}
int main() {
int num1;
printf("Number: ");
scanf("%d", &num1); //Zahl 1
char op = 'X'; // placeholder value
while (op != '=') {
printf("\nOperator: ");
scanf(" %c", &op); //Operator
if (op == '=') { //Überprüfung ob User weiterrechnen will
printf("Final result: %d\n", num1);
printf("Number of positive: %d\n", poscount);
printf("Number of negatives: %d\n", negcount);
break;
}
printf("\nNumber: ");
int num2;
scanf("%d", &num2); //Zahl
if (op == '+') {
num1 = add(num1, num2); //Addition
}
else if (op == '-'){
num1 = sub(num1, num2); //Subtraktion
}
else if (op == '*'){
num1 = mul(num1, num2); //Multiplikation
}
else if (op == '/'){ //Divisionen
if (num2 == 0) {
printf("Division by 0."); //Ausnahme Division durch 0
printf("No new result.");
}
else {
num1 = myDiv(num1, num2);
}
}
else {
printf("Unknown operator");
}
}
return 0;
}
How do i proplerly clear input buffer since fflush(stdin) is undefined and only available in some compilers,
My plan is to clear input since after looping back it still use the buffered input rather than getting a new input.
Here is my code:
#include <stdio.h>
#include <stdbool.h>
//bool function
bool isInteger(double val)
{
int truncated = (int)val;
return (val == truncated);
}
int main()
{
//local variable
double result, a, b;
char oper, option = 'y';
//loop
while(option == 'y')
{
system("cls");
printf("Enter number and operator to solve:\n\nExapmple [a + b][a - b][a * b][a / b]\n");
scanf("%lf %c %lf", &a, &oper, &b);
// nested if
if(isInteger(a) && isInteger(b))
{
if(oper == '+')
{
result = a + b; //calculation
printf("%.1lf %c %.1lf = %.1lf\n\n", a, oper, b, result); //ouput result
}
else if(oper == '-')
{
result = a - b; //calculation
printf("%.1lf %c %.1lf = %.1lf\n\n", a, oper, b, result); //ouput result
}
else if(oper == '*')
{
result = a * b; //calculation
printf("%.1lf %c %.1lf = %.1lf\n\n", a, oper, b, result); //ouput result
}
else if(oper == '/')
{
result = a / b; //calculation
printf("%.1lf %c %.1lf = %.1lf\n\n", a, oper, b, result); //ouput result
}
else
{
//output error
printf("Invalid Operater!\n");
}
}
else
{
//output error
printf("Input is not a digit!\n");
}
//output selection
printf("Do you want to retry y/n?");
option = getch();
} // end loop
}
I only use scanf since we are still in scanf and printf.
Please help me out, this is our first project in college.
I am just making a simple calculator and would like to know
how could I make my calculator loop back to the start when an invalid operator/float is entered; to ask the user to input everything again. Basically restarting it.
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int main()
{
double num1;
double num2;
char op;
printf("Input a number: ");
scanf("%lf", &num1);
printf("Enter operator (+,-,*,/,^): ");
scanf(" %c", &op);
printf("Enter the second number: ");
scanf(" %lf", &num2);
if (op == '+')
{
printf("%f", num1 + num2);
}
else if (op == '-')
{
printf("%f", num1 - num2);
}
else if (op == '/')
{
printf("%f", num1 / num2);
}
else if (op == '*')
{
printf("%f", num1 * num2);
}
else if (op == '^')
{
printf("%f", pow(num1,num2));
}
else
{
printf("Invalid operator entered");
}
return 0;
}
I would do it another way to avoid \n scanf problems
#define MAXNUMSTR 100
int calc(void)
{
char line[MAXNUMSTR];
double num1;
double num2;
double res;
do
{
printf("\nInput first number: ");
if(!fgets(line, MAXNUMSTR -1, stdin)) return 0;
}while(sscanf(line, "%lf", &num1) != 1);
do
{
printf("\nInput second number: ");
if(!fgets(line, MAXNUMSTR -1, stdin)) return 0;
}while(sscanf(line, "%lf", &num2) != 1);
printf("\nEnter operator (+,-,*,/,^, x): ");
if(!fgets(line, MAXNUMSTR -1, stdin)) return 0;
switch(line[0])
{
case '+':
res = num1 + num2;
break;
case '-':
res = num1 - num2;
break;
case '*':
res = num1 * num2;
break;
case '/':
if(num2 == 0.0)
{
printf("\nDivision by zero\n");
return 1;
}
res = num1 / num2;
break;
case '^':
res = pow(num1, num2);
break;
case 'x':
return 0;
default:
printf("\nInvalid operation\n");
return 1;
}
printf("\n%f %c %f = %f\n", num1, num2, res);
return 1;
}
int main(void)
{
while(calc());
return 0;
}
Insert the whole logic in an infinite loop like below.
while(1) {
printf("Input a number: ");
scanf("%lf", &num1);
printf("Enter operator (+,-,*,/,^): ");
scanf(" %c", &op);
printf("Enter the second number: ");
scanf(" %lf", &num2);
if (op == '+')
{
printf("%f", num1 + num2);
}
else if (op == '-')
{
printf("%f", num1 - num2);
}
else if (op == '/')
{
printf("%f", num1 / num2);
}
else if (op == '*')
{
printf("%f", num1 * num2);
}
else if (op == '^')
{
printf("%f", pow(num1,num2));
}
else
{
printf("Invalid operator entered");
}
}
I want to make a simple C calculator only with "IF" and "IF ELSE" conditions and it don't let me choose an operator ("+, -, * or /"), just appear my last if condition.
#include <stdio.h>
int main(){
printf("\tCalculadora\n\n");
int num1, num2, total;
char oper;
printf("Introduza o primeiro numero: \n");
scanf("%d", &num1);
printf("Introduza o segundo numero: \n");
scanf("%d", &num2);
printf("Escolha a operacao que quer realizar!\n\n");
scanf("%c", &oper);
if(oper == '+'){
printf("O resultado e: %d", num1+num2);
}
else if(oper == '-'){
printf("O resultado e: %d", num1-num2);
}
else if(oper == '*'){
printf("O resultado e: %d", num1*num2);
}
else{
printf("O resultado e: %d", num1/num2);
}
getchar();
getchar();
}
I avoid scanf() and its cousins. Here is a version of your calculator that uses fgets() for the input. It also uses double for the operands.
#include <stdio.h>
#include <stdlib.h>
#define ISIZE 100 // arbitrarily large
int main(){
double num1, num2;
int oper;
char inp[ISIZE+1] = "";
printf("\tCalculadora\n\n");
printf("Introduza o primeiro numero: "); // 1st operand
fgets (inp, ISIZE, stdin);
num1 = atof (inp);
printf("Introduza o segundo numero: "); // 2nd operand
fgets (inp, ISIZE, stdin);
num2 = atof (inp);
printf("Escolha a operacao que quer realizar! "); // operator
fgets (inp, ISIZE, stdin);
oper = inp[0];
printf ("O resultado e: %f %c %f = ", num1, oper, num2);
switch (oper) {
case '+': printf("%f\n", num1+num2); break;
case '-': printf("%f\n", num1-num2); break;
case '*': printf("%f\n", num1*num2); break;
case '/': if (num2!=0) printf("%f\n", num1/num2);
else printf ("Divisão por zero!\n");
break;
default: printf("Eu não sei o que operador\n");
}
return 0;
}
This
scanf("%c", &oper);
should change to
scanf(" %c", &oper);
so you let scanf() ignore the '\n' left by previous scanf()s.
I was also trying to apply my knowladage of C in a simple calculator and came across you question. In order to respect your if...else request I've come up with this solution. I hope this helps.
#include <stdio.h>
void sayHello( ) {
printf("Hello\n"); }
// to say hello to the user
int add( int num1, int num2) {
num1 = num1 + num2;
return num1;
}
int minus( int num1, int num2) {
num1 = num1 - num2;
return num1;
}
int times( int num1, int num2) {
num1 = num1 * num2;
return num1;
}
int divide( int num1, int num2) {
num1 = num1 / num2;
return num1;
}
// This is to declare the calculations
void flush_input(){
int ch;
while ((ch = getchar()) != '\n' && ch != EOF); }
// This is to flush the scanf values
// Kudos to Huw Collingbourne, Udemy Teacher
int main(int argc, char **argv) {
char c;
char f;
int n1;
int n2;
int total;
// n1 = ' ';
// n2 = ' ';
sayHello();
do {
c = ' ';
printf("Insert the type of Calculation you want to make:\n");
printf("A(d)dition, Subs(t)raction, Mu(l)tiplication, Di(v)ision: ");
c = getchar();
if(c == 'd') {
printf("\nInsert the first number:");
scanf("%d", &n1);
printf("Insert the second number:");
scanf("%d", &n2);
total = add( n1, n2 );
printf("%d plus %d equals to %d\n", n1, n2, total );
flush_input(); } else {
if( c == 't') {
printf("insert the base number:");
scanf("%d", &n1);
printf("Insert the subtracting number:");
scanf("%d", &n2);
total = minus( n1, n2 );
printf("The difference between %d and %d is %d\n", n1, n2, total );
flush_input(); } else {
if( c == 'l') {
printf("insert the first number:");
scanf("%d", &n1);
printf("Insert second number:");
scanf("%d", &n2);
total = times( n1, n2 );
printf("%d times %d equals %d\n", n1, n2, total );
flush_input(); } else {
if( c == 'v') {
printf("insert the first number:");
scanf("%d", &n1);
printf("Insert second number:");
scanf("%d", &n2);
total = divide( n1, n2 );
printf("%d divided by %d equals %d\n", n1, n2, total );
flush_input();
} else {
printf("I couln't understand the instruction\n Reseting program\n");
}
}
}
}
f = ' ';
printf("\nDo you wish to make another calculation?\n");
printf("Choose (y)es or (n)ot: ");
f = getchar();
// scanf("%c", &c);
getchar();
} while( f != 'n' );
printf("\nThat's all folks!\n");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
//declaration of function
float cal (float a, float b, char o);
int main(int argc, char *argv[])
{
// declaration of variable
float num1,num2;
int inum1,inum2;
char o;
//initialization of variable
num1=0;
num2=0;
//input
printf("Enter 1st number\n");
scanf("%f",&num1);
//input
printf("operator\n");
scanf(" %c", &o);
//input
printf("Enter 2nd number\n");
scanf(" %f", &num2);
inum1=num1;
inum2=num2;
if(cal(num1,num2,o)==0)
{
printf("Math Error");
}
if(cal(num1,num2,o)==1)
{
printf("%d",inum1%inum2);
}
else
printf("%.3f\n",cal(num1,num2,o));
return 0;
}
//definening function
float cal (float a, float b, char o)
{
if (o=='+')
return a+b;
if (o=='-')
return a-b;
if (o=='*')
return a*b;
if (o=='%')
return 1;
if (o=='/')
if (b!=0)
return a/b;
if (b==0)
return 0;
}
#include<stdio.h>
int main()
{
int choice;
printf("Enter 1 for Programmers Name and ID\n");
printf("Enter 2 to Perform Integer Operation\n");
printf("Enter 3 to Perform Floating Point Operation\n");
scanf("%d", &choice);
system("CLS");
if (choice == 1)
printf("Connor \n000000000\n");
else if (choice == 2)
{
char c;
int num1, num2;
printf("Enter operator:");
scanf("%c", &c);
getchar();
printf("Enter two integer's :");
scanf("%d %d", &num1, &num2);
switch (c)
{
case '+':
printf("%d + %d = %d", num1, num2, num1 + num2);
break;
case '-':
printf("%d - %d = %d", num1, num2, num1 - num2);
break;
case '*':
printf("%d * %d = %d", num1, num2, num1*num2);
break;
case '/':
printf("%d / %d = %d", num1, num2, num1 / num2);
break;
default:
printf("The value of c = '%c'\n");
system("pause");
return(0);
}
}
else if (choice == 3)
printf("Enter two \n");
system("pause");
return(0);
}
I need a little help figuring out a small problem with the operations part of this code.......everything works out as in can put in the operator and the integers but I do not get the output from the switch.
this should definitely work
#include<stdio.h>
int main()
{
int choice;
printf("Enter 1 for Programmers Name and ID\n");
printf("Enter 2 to Perform Integer Operation\n");
printf("Enter 3 to Perform Floating Point Operation\n");
scanf("%d", &choice);
getchar();
if (choice == 1)
printf("Connor \n000000000\n");
else if (choice == 2)
{
char c;
int num1, num2;
printf("Enter operator:");
scanf("%c", &c);
printf("Enter two integer's :");
scanf("%d %d", &num1, &num2);
switch (c)
{
case '+':
printf("%d + %d = %d", num1, num2, num1 + num2);
break;
case '-':
printf("%d - %d = %d", num1, num2, num1 - num2);
break;
case '*':
printf("%d * %d = %d", num1, num2, num1*num2);
break;
case '/':
printf("%d / %d = %d", num1, num2, num1 / num2);
break;
default:
printf("The value of c = '%c'\n" , c);
return(0);
}
}
else if (choice == 3)
printf("Enter two \n");
}
Change:
scanf("%c", &c);
getchar();
to:
scanf(" %c", &c);
Add an \n to each of these:
printf("%d + %d = %d\n", num1, num2, num1 + num2);
^^
Actually provide a char when you tell printf() to print one:
printf("The value of c = '%c'\n", c);
^^^
and it should work for you. Revised code, removing all the system() nonsense:
#include <stdio.h>
int main(void)
{
int choice;
printf("Enter 1 for Programmers Name and ID\n");
printf("Enter 2 to Perform Integer Operation\n");
printf("Enter 3 to Perform Floating Point Operation\n");
scanf("%d", &choice);
if ( choice == 1 ) {
printf("Connor \n000000000\n");
}
else if ( choice == 2 ) {
char c;
int num1, num2;
printf("Enter operator:");
scanf(" %c", &c);
printf("Enter two integers :");
scanf("%d %d", &num1, &num2);
switch ( c ) {
case '+':
printf("%d + %d = %d\n", num1, num2, num1 + num2);
break;
case '-':
printf("%d - %d = %d\n", num1, num2, num1 - num2);
break;
case '*':
printf("%d * %d = %d\n", num1, num2, num1 * num2);
break;
case '/':
printf("%d / %d = %d\n", num1, num2, num1 / num2);
break;
default:
printf("The value of c = '%c'\n", c);
break;
}
} else if ( choice == 3 ) {
printf("Enter two \n");
}
else {
printf("Invalid choice.\n");
}
return 0;
}
with sample output:
paul#thoth:~/src/sandbox$ ./cal
Enter 1 for Programmers Name and ID
Enter 2 to Perform Integer Operation
Enter 3 to Perform Floating Point Operation
2
Enter operator:*
Enter two integers :4 6
4 * 6 = 24
paul#thoth:~/src/sandbox$