Builidng a calculator in c language can use a previous result - c

i got problem with this calculator which i need to use the previous result of previous operartion (if i want to ) but when i do it it gives correct if only give it the same previous operation
here is the code :
#include<stdio.h>
#include<math.h>
double addition (double a, double b)
{
double add;
add=a+b;
return add;
}
double soustraction (double a, double b)
{
double sous;
sous=a-b;
return sous;
}
double multiplication (double a,double b)
{
double multi;
multi=a*b;
return multi;
}
double division (double a, double b)
{
double div;
div=a/b;
return div;
}
double reste_de_division (int a,int b)
{
double rest;
rest=a%b;
return rest;
}
double puissance( double a,double b)
{
int i;
double r;
i = 0;
r = 1;
while (i < b){
r = r * a;
i ++;
}
return r;
}
double factorielle (double a)
{
int i;
double facto;
facto=1;
for(i=0;i<a;i++)
{facto=(a-i)*facto;
}
return facto;
}
double PGCD (int a,int b)
{
int i;
double pgcd;
for(i=1; i <= a && i <= b; ++i)
{
if(a%i==0 && b%i==0)
pgcd = i;
}
return pgcd;
}
double PPCM (int a,int b)
{
int ppcm;
ppcm = (a > b) ? a : b;
while(ppcm%a !=0 || ppcm%b !=0)
ppcm=ppcm+1;
return ppcm;
}
double inverse (double a)
{
double inv;
inv=1/a;
return inv;
}
int main(){
double a,b,r;
char ch;
printf("\n***************************************\n");
printf (" \n + Addition \t \t - Subtraction \n * Multiplication \t / Division \n Reste de division \t c Puissance \n ! Factorielle \t \t g PGCD \n p PPCM \t \t i Inverse \n q Quitter \n");
printf("\n***************************************\n");
printf("Donner les deux nombres et l'operation:\n");
do
{b=r;
scanf("%lf %lf %c",&a,&b,&ch);
switch (ch)
{case '+':
r=addition(a,b);
printf("%lf\n",r);
break;
case '-':
r=soustraction(a,b);
printf("%lf\n",r);
break;
case '*':
r=multiplication(a,b);
printf("%lf\n",r);
break;
case '/':
r=division(a,b);
printf("%lf\n",r);
break;
case '%':
printf("%lf\n",reste_de_division(a,b));
break;
case 'c':
printf("%lf\n",puissance(a,b));
break;
case '!':
printf("%lf\n",factorielle(a));
break;
case 'g':
printf("%lf\n",PGCD(a,b));
break;
case 'p':
printf("%lf\n",PPCM(a,b));
break;
case 'i':
printf("%lf\n",inverse(a));
break;
}
}while(ch !='q');
return 0;
}
Sorry for my bad english
example:
5 6 +
11
6 +
17
3 -
20 //this is error, it's supposed to give 14 not 20

Your problem is here:
scanf("%lf %lf %c",&a,&b,&ch);
You expect the user to always input two doubles and one character. If the user only gives one double and one character, the value of ch (and b) is unchanged and the program will do the same operation as it did the last time.
Example:
First input:
5 6 +
This will make a equal 6, b equal 5 and ch equal +. Consequently the program will add the two numbers 5 and 6 and produce the result 11 which is stored in b.
Next input:
1 -
This will make a equal one but leave both b and ch unchanged, i.e. b is still equal 11 and ch is still equal +. Consequently the program will add the two numbers 1 and 11 and produce the result 12 which is stored in b.
This is just one example of things that can go wrong when doing scanf("%lf %lf %c",&a,&b,&ch); There are other input sequences that will lead to (even more) bizar output.
You need a much more strict parsing of user input. The scanf functions isn't good for that. Consider using fgets to read a whole line and the parse it afterwards. With care that can be done using sscanf.

Related

Why won't my result update after the first iteration(?)

#include <stdio.h>
#include <math.h>
void scan_data(char *op, float *operand);
float do_next_op(char op, float operand, float *accumulator);
int main(void)
{
char op;
float operand;
float accumulator = 0;
do
{
printf(" + add\n - subtract\n * multiply\n / divide\n ^ power\n q quit\n\n");
scan_data(&op, &operand);
if(op == 'q' || op == 'Q')
{
printf("Final result is %.1f\n", do_next_op(op, operand, &accumulator));
break;
}
else
{
printf("result so far is %.1f\n", do_next_op(op, operand, &accumulator));
}
}while(op != 'q' || op == 'Q');
}
void scan_data(char *op, float *operand)
{
scanf("%c%f",op, operand);
}
float do_next_op(char op, float operand, float *accumulator)
{
switch(op)
{
case('+'):
*accumulator = *accumulator + operand;
break;
case('-'):
*accumulator = *accumulator - operand;
break;
case('*'):
*accumulator = *accumulator * operand;
break;
case('/'):
*accumulator = *accumulator / operand;
break;
case('^'):
*accumulator = pow(*accumulator,operand);
break;
}
return *accumulator;
}
I'm trying to code a "simple" calculator where if i type
+5.0
result so far is 5.0
^2
result so far is 25.0
/ 2.0
result so far is 12.5
Q 0
final result is 12.5
The problem is, the code will "correctly" output the first operation but if i put anymore operation after that I doesn't update to the new value.
How can I fix the code to do what I intend to do?
I'm sorry in advance if my question wording and format is off, I don't know how to ask it in a proper way.
the problem is in the statement:
scanf("%c%f",op, operand);
After the first iteration, there is a left over newline in stdin
That newline is a 'white space', typically \n
That 'white space must be consumed before the %c rather than the %c consuming it. Suggest:
scanf(" %c%f",op, operand);
where the leading space in the format string consumes that 'white space'
regarding the statement:
*accumulator = pow(*accumulator,operand);
the pow() function expects to be working with double values, not float values. Suggest:
*accumulator = powf(*accumulator,operand);
Notice this is calling powf() not pow()

Calculator program requires + and - to be entered twice

I am writing a simple calculator program to add, subtract, multiply, divide and do exponential equations. The program must repeat until "q0" is entered and it must have two functions called by the main function like I have written. The problem is when I run the program the first number shows up fine and then I can multiply, divide, and do exponential functions fine but if I want to add or subtract I must enter the + or - twice for it to count it. This is the program I have written:
#include <stdio.h>
#include <math.h>
void scan_data(char *oprter, double *oprand);
void do_next_op(char oprter, double oprand, double *accum);
int
main(void)
{
double nmber, /* input/output - operand */
total; /* output - final result */
char sign; /* input/output - operator */
total = 0;
do {
scan_data(&sign, &nmber);
do_next_op(sign, nmber, &total);
} while (sign != 'q');
printf("Final result is %.2f", total);
return (0);
}
/*
* Gathers operator and operand to perform calculation
* Post: results are stored in cells pointed to by oprter, and oprand
*/
void
scan_data(char *oprter, /* input - amount being withdrawn */
double *oprand) /* output - number of tens */
{
double amount;
amount = 0;
scanf("%c", &*oprter);
scanf("%lf", &amount);
*oprand = amount;
}
/*
* Performs calculation and displays results
* Pre: oprter and oprand are defined
* Post: function results are stored in cell pointed to by accum
*/
void
do_next_op(char oprter,
double oprand,
double *accum)
{
double tot_amount;
tot_amount = *accum;
switch(oprter)
{
case '+':
tot_amount = (tot_amount + oprand);
printf("result so far is %.2f\n", tot_amount);
break;
case '-':
tot_amount = (tot_amount - oprand);
printf("result so far is %.2f\n", tot_amount);
break;
case '*':
tot_amount = tot_amount * oprand;
printf("result so far is %.2f\n", tot_amount);
break;
case '/':
tot_amount = tot_amount / oprand;
printf("result so far is %.2f\n", tot_amount);
break;
case '^':
tot_amount = pow(tot_amount, oprand);
printf("result so far is %.2f\n", tot_amount);
break;
}
*accum = tot_amount;
}
An example of what it is doing follows:
+5
result so far is 5.00
+5
-5
++5
result so far is 10.00
--5
result so far is 5.00
*2
result so far is 10.00
/2
result so far is 5.00
^2
result so far is 25.00
q0
Final result is 25.00
The problem is most likely that scanf leaves the newline in the input buffer when you do
scanf("%lf", &amount);
That means that the next call to
scanf("%c", oprter);
it will read that newline.
This can be solved by asking scanf to read and skip all leading whitespace by adding a single space to the scanf format string like
scanf(" %c", oprter);
// ^
// |
// Note space here

C Calculator with a lot of functions in functions in functions

I had programmed first an easy calculator. Now I would like to outsource the individual program components in Functions. The Problem is the switch-part.The program always gives me the default message:Bad operator. Please take a look and give me some tipps.Is something wrong with the pointers and double-pointers?
Here is my code:
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
void newcalc(char*,double*,char*,double*);
double switchfunk(double**, char**, double**);
double readcalc(double**,char**,double**);
double addition(double,double);
double subtraction(double,double);
double multiplication(double,double);
double division(double,double);
int main()
{
double a=0, b=0;
char op='R', restart = 'Y';
newcalc(&restart,&a,&op,&b);
fflush(stdin);
getchar();
return 0;
}
double switchfunk(double** x, char** opp, double** y)
{
printf("\n ---CALCULATOR--- \n\n\n");
switch (**opp)
{
case '+':printf("%lf + %lf = %lf\n", **x, **y, addition(**x, **y)); break;
case '-':printf("%lf - %lf = %lf\n", **x, **y, subtraction(**x, **y)); break;
case '*':printf("%lf * %lf = %lf\n", **x, **y, multiplication(**x, **y)); break;
case '/':printf("%lf / %lf = %lf\n", **x, **y, division(**x, **y)); break;
default:printf("bad operator!");
}
return 0;
}
void newcalc(char* restart,double* x, char* opp, double* y)
{
while (restart != (char*)'N')
{
readcalc(&x, &opp, &y);
switchfunk(&x, &opp, &y);
printf("New Calc? (Y,N) \n");
fflush(stdin);
scanf("%c", &restart);
if (restart != (char*)'Y'&&restart != (char*)'N')
{
printf("Bad input!");
}
}
}
double readcalc(double** x,char** opp,double** y)
{
printf("\n Type your calculation!(z.B.4+7)\n");
scanf("%lf%c%lf",x,opp,y);
return 0;
}
double addition(double a,double b)
{
double c = 0;
c = a + b;
return c;
}
double subtraction(double a, double b)
{
double c = 0;
c = a - b;
return c;
}
double multiplication(double a, double b)
{
double c = 0;
c = a*b;
return c;
}
double division(double a, double b)
{
double c = 0;
c = a / b;
return c;
}
Best regards!
You have so many problems in your code, most of them related to your use of pointers. Here's one problem:
In the newcalc function you have the following condition in a loop:
restart != (char*)'N'
That will not work as you expect, in fact it will always be true and give you an infinite loop.
The reason is that restart is a pointer which points to the location of the local restart variable in the main function. It will never be the same as (char *) 'N' (which is a pointer pointing to address 78).
How to solve this specific problem? To start with, don't have it as an argument, declare it as a local (non-pointer!) variable:
char restart = 'y';
Then use it normally in the loop condition
while (restart == 'y' || restart == 'Y') { ... }
And to hint to more pointer problems, remember that scanf want a pointer to the variable where to store the value?
But in e.g. the readcalc function the variables x, opp and y are pointers to pointers to where the data should be stored, and yet you pass these pointers-to-pointer to scanf:
scanf("%lf%c%lf",x,opp,y);
Here, you should use pointers as argument to readcalc function, but not pointers-to-pointers.
In other words, it should be declared as
double readcalc(double*,char*,double*);
You most likely have many other problems with your (unnecessary) use of pointers and pointers-to-pointers, but these were the ones that really stood out.
I think you are misusing pointers and using addresses rather than the values themselves. Also, you are using pointers to pointers while you are not in need to do so. Take a look at the following code.
#include <stdio.h>
#include <stdlib.h>
void newcalc (char*,double*,char*,double*);
double switchfunk(double*, char*, double*);
double readcalc(double*,char*,double*);
double addition(double,double);
double subtraction(double,double);
double multiplication(double,double);
double division(double,double);
int main()
{
double a=0, b=0;
char op='R', restart = 'Y';
newcalc(&restart,&a,&op,&b);
fflush(stdin);
getchar();
return 0;
}
double switchfunk (double* x, char* opp, double* y)
{
printf("\n ---CALCULATOR--- \n\n\n");
switch ( *opp )
{
case '+':
printf("%lf + %lf = %lf\n", *x, *y, addition(*x, *y));
break;
case '-':
printf("%lf - %lf = %lf\n", *x, *y, subtraction(*x, *y));
break;
case '*':
printf("%lf * %lf = %lf\n", *x, *y, multiplication(*x, *y));
break;
case '/':
printf("%lf / %lf = %lf\n", *x, *y, division(*x, *y));
break;
default:printf("bad operator!");
}
return 0;
}
void newcalc(char* restart,double* x, char* opp, double* y)
{
while ( *restart == 'Y' || *restart == 'y')
{
readcalc(x, opp, y);
switchfunk(x, opp, y);
printf("New Calc? (Y,N) \n");
fflush(stdin);
scanf("%c", restart);
// if (restart != (char*)'Y'&&restart != (char*)'N')
// {
// printf("Bad input!");
// }
}
}
double readcalc(double* x,char* opp,double* y)
{
printf("\n Type your calculation!(z.B.4+7)\n");
scanf("%lf%c%lf",x,opp,y);
return 0;
}
double addition(double a,double b)
{
return a + b;
}
double subtraction(double a, double b)
{
return a - b;
}
double multiplication(double a, double b)
{
return a*b;
}
double division(double a, double b)
{
return a / b;
}

3 Pointers in 1 Function - Calculator doesn´t work

I've a problem with a function in my calculator-program. The function returns me back only 0 values​​. I want that:
Input:3+4
Output:7
I have worked with pointers to use the call by reference method. Please give me some tips.
The mistake is in the function readcalc. If I write the whole syntax in the main program it works.
Here is my code.
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
double readcalc(double*,char*,double*);
double addition(double,double);
double subtraction(double,double);
double multiplication(double,double);
double division(double,double);
int main()
{
double a=0, b=0;
char op='R', restart = 'Y';
while (restart != 'N')
{
readcalc(&a,&op,&b);
printf("%lf%lf", a, b);
printf("\n ---CALCULATOR--- \n\n\n");
switch (op)
{
case '+':printf("%lf + %lf = %lf\n", a, b, addition(a, b)); break;
case '-':printf("%lf - %lf = %lf\n", a, b, subtraction(a, b)); break;
case '*':printf("%lf * %lf = %lf\n", a, b, multiplication(a, b)); break;
case '/':printf("%lf / %lf = %lf\n", a, b, division(a, b)); break;
default:printf("bad operator!");
}
printf("New Calc? (Y,N) \n");
fflush(stdin);
scanf("%c", &restart);
if (restart != 'Y'&&restart != 'N')
{
printf("Bad input!");
}
}
fflush(stdin);
getchar();
return 0;
}
double readcalc(double* x,char* opp,double* y)
{
printf("\n Type your calculation!(z.B.4+7)\n");
scanf("%lf%c%lf", &x, &opp, &y);
return 0;
}
double addition(double a,double b)
{
double c = 0;
c = a + b;
return c;
}
double subtraction(double a, double b)
{
double c = 0;
c = a - b;
return c;
}
double multiplication(double a, double b)
{
double c = 0;
c = a*b;
return c;
}
double division(double a, double b)
{
double c = 0;
c = a / b;
return c;
}
What can I change?
The problem with readcalc is that you pass the pointer to the pointer as argument to scanf. The variables are already pointers, so you don't have to use the address-of operator to get a pointer, as then you get pointers to the pointers.
Also be careful with the scanf format, as the "%c" format doesn't skip leading whitespace, so if you enter e.g. 1 +2 then the scanf call will not be able to read the operator or the second number.
void readcalc(double* x,char* opp,double* y)
{
printf("\n Type your calculation!(z.B.4+7)\n");
scanf("%lf%c%lf", x, opp, y); // <== no &'s
}
Your readcalc function invokes
scanf("%lf%c%lf", &x, &opp, &y);
on pointers, int *x, etc...
When you place it inline in main, it works on the addresses of the variables.
Change it to
scanf("%lf%c%lf", x, opp, y);
At a suitable warning level, you may have seen warning.
While you are there, readcalc returns a double, which you never use. Perhaps it should simply be void?

Unexpected output using the switch statement for this complex logic

I am trying to use a switch statement for 3 conditions. Conditions were:
When a, b, and c are all zero, any value of x is a solution. Print: Any value of x is a solution.
When a and b are zero and c is not, no solution exists. Print: No solution exists.
When a is zero and b is not zero, the only solution is x = -c/b. Calculate the value of x and print the solution.
When I tried to run my program, it displayed the wrong results. My input were
a = 0
b = 0
c = 0
So it's supposed to print "Any value of x is a solution", but it didn't.
My program is:
#include <stdio.h>
//Function declarations
void getData (int* a, int* b, int* c);
float calculateX (int a, int b, int c);
//===================================================
int main (void)
{
//Local declarations
int a;
int b;
int c;
float x;
//Statements
getData (&a, &b, &c);
calculateX (a, b, c);
int temp;
printf("\nEnter an integer and press enter to exit the program: ");
scanf("%d", &temp);
return 0;
}
//----------------------------------------------------
void getData (int* a, int* b, int* c)
{
printf("Enter three integers: ");
scanf("%d %d %d", a, b, c);
return;
}
//----------------------------------------------------
float calculateX (int a, int b, int c)
{
float x;
printf("Input is: %d %d %d\n", a, b, c);
switch(a, b, c)
{
case 1: (a, b, c == 0);
printf("Any value of x is a solution.");
break;
case 2: (a, b == 0 && c!= 0);
printf("No solution exists.");
break;
case 3: (a == 0 && b!= 0);
x = (float)(-c/b);
printf("The value of x is: %.1f", x);
break;
default: printf("Cannot calculate.");
}
return a, b, c;
}
And my output was:
Enter three integers: 0 0 0
Input is: 0 0 0
Cannot calculate.
Enter an integer and press enter to exit the program:
This is not how a switch statement works. It compiles, but for very obscure reasons. Obviously, it doesn't do what you expect when it runs.
Generally speaking, you use a switch statement on a single expression, and each of the case labels represents one possible value of that expression. e.g.:
switch (x)
{
case 1:
// Code here runs when x == 1
break;
case 2:
// Code here runs when x == 2
break;
default:
// Code here runs for all other values of x
break;
}
In your application, you want to test multiple variables, and combine them in complex ways. There is no neat way to do that with switch. You should consider a set of if statements instead.
Is there any reason you have to use switch? Just do
if (a == 0 && b == 0 && c == 0)
...
else if (a == 0 && b == 0 && c != 0)
....
...
Actually, here's a valid way to use the switch statement for this problem:
switch ((a != 0) * 4 + (b != 0) * 2 + (c != 0))
{
case 0: // a, b, c == 0
printf("Any value of x is a solution.");
break;
case 1: // a, b == 0 && c!= 0
printf("No solution exists.");
break;
case 2: // a == 0 && b!= 0
case 3:
x = (float)(-c/b);
printf("The value of x is: %.1f", x);
break;
default:
printf("Cannot calculate.");
}
I've based this on your code, except that I use conditionals (which evaluate to 0 or 1) to encode the state of each variable (zero or not, respectively) in the expression, assigning each to a separate bit. The switch then decodes it -- the interesting part for you, as a beginner, is that case 2 falls through to case 3 because we don't care whether c is zero.
Your code has some other issues, but I'm restricting myself to the switch that you asked about. Best of luck.

Resources