Creating my own calcutor but program doesnt work - c

I decided to make a calcutor using code but my program just wont work.
When i enter my operand and new number it wont seem to scan the operand and number and it wont start the loop.
Thanks for the help.
#include <stdio.h>
#include <math.h>
float add(float x,float y);
float sub(float x,float y);
float div(float x,float y);
float exp(float x,float y);
float mult(float x,float y);
int main(){
float y,x;
char op;
printf("Type in a number\n");
scanf("%f",&x);
printf("Type in your operand and desired number\n");
scanf("%c",&op);
scanf("%f",&y);
while (!(op=='q')){
if(op=='+'){
printf("Your result is %.1f\n",add(x,y));
scanf("%c",&op);
scanf("%f",&y);
}
else if(op=='-'){
printf("Your result is %.1f\n",sub(x,y));
scanf("%c",&op);
scanf("%f",&y);
}
else if(op=='*'){
printf("Your result is %.1f\n",mult(x,y));
scanf("%c",&op);
scanf("%f",&y);
}
else if(op=='/'){
printf("Your result is %.1f\n",div(x,y));
scanf("%c",&op);
scanf("%f",&y);
}
else if(op=='^'){
printf("Your result is %.1f\n",exp(x,y));
scanf("%c",&op);
scanf("%f",&y);
}
}
printf("Your final result is %.1f\n",x);
return(0);
}
float add(float x,float y){
return (x+y);
}
float sub(float x,float y){
return (x-y);
}
float div(float x,float y){
return (x/y);
}
float exp(float x,float y){
x=pow(x,y);
return(x);
}
float mult(float x,float y){
return (x*y);
}

when you do
scanf("%c",&op);
you read first char that is in the input buffer. previous scanf left \n char in it, so you read that char.
What you want to do, is to get rid of all what's left behind scanf.
while(getchar()!='\n')
continue;
That will empty the buffer before you try to read.
Every use of scanf here will leave new line character in the buffer so to get rid of him, use above loop every time you try to read a character from input and you know that newline is there.

I think what's happening is that the newline character (the return/enter key) is left over in the input stream after the scanf("%f",&y); call and that's what being stored as the single character in the scanf("%c",&op); call.
So you'll need to discard the newline character at that point. Simplest way is to call scanf("%c",&op); twice when you need to read the single character. This should work on Mac and Unix. For Windows, you may need to read the character three times because Windows often considers the sequence "\r\n" as a newline sequence.
For portability, you can use a loop like this:
do {
op = getchar();
} while (op == '\n' || op == '\r');
And remove the scanf("%c",&op);. This loop replaces it.
Another option is to ask scanf itself to discard initial whitespace.
scanf(" %c",&op);
// ^ space
Also, see my answer to this very similar question.

Related

where I made the mistake and how to fix it?

#include <stdio.h>
float result(int x, int y);
float result1(int x, int y);
int main()
{
int x,y;
char z;
printf("enter x:\n");
scanf("%d",&x);
printf("enter y:\n");
scanf("%d",&y);
printf("enter z:\n");
scanf("%s",&z);
if (z=='*')
{printf("the result is %.2f",result(x,y));}
else if (z=='/')
{printf("the result is %.2f",result1(x,y));}
else
{printf("there is an error");}
return 0;
}
float result(int x, int y)
{
float r=x*y;
return r;
}
float result1(int x, int y)
{
float r1=x/y;
return r1;
}
```so this is my code. my out put is ---
enter x:
4
enter y:
5
enter z:
*
the result is 0.00
Question was -
take two integer number from user x and y and a character z. the result should be in float.
if z is * then it should be x*y
if z is / then it should be x/y
if z is none of the above then it will return 0
you need to use function .
so it was the question, I know it can be done by switch case but I wanted to try if else.
The problem is this:
scanf("%s",&z);
The format specifier %s is used to read null-terminated strings. The variable z is a single character, it can only hold the empty string (which is only the null-terminator and nothing else).
Any other input will write somewhere in memory and lead to undefined behavior.
If you want to read a single character use the format %c. But be careful, the newline that the Enter key added from previous input will also be read with %c, and you need to ask scanf to skip and ignore it. This is done by adding a leading space to the format string.
So the call should be:
scanf(" %c",&z);

Using printf() to output the correct number of decimal places?

When I enter 2, I wish to get this output:
value: 2.4
But when I do the multiplication, I am getting this:
value: 2.400000
This is my code:
#include <stdio.h>
int main()
{
float num;
float result;
printf("Number: ");
scanf("%f", &num);
result = num * 1.2;
printf("Result: %f", result);
}
What can I do?
You can specify how many digits you want to print after the decimal point by using %.Nf where N is the number of digits after the decimal point. In your use case, %.1f: printf("Result: %.1f", result).
There are some other issues in your code. You are making use of scanf(), but you are not checking its return value. This may cause your code to break.
scanf() returns the number of arguments it successfully parsed. If, for any reason, it fails, it doesn't alter the arguments you gave it, and it leaves the input buffer intact. This means whenever you try again and read from the input buffer, it will automatically fail since
it previously failed to parse it, and
it didn't clear it, so it's always there.
This will result in an infinite loop.
To solve the issue, you need to clear the input buffer in case scanf() fails. By clearing the buffer, I mean read and discard everything up until a newline (when you previously pressed Enter) is encountered.
void getfloat(const char *message, float *f)
{
while (true) {
printf("%s: ", message);
int rc = scanf("%f", f);
if (rc == 1 || rc == EOF) break; // Break if the user entered a "valid" float number, or EOF is encountered.
scanf("%*[^\n]"); // Read an discard everything up until a newline is found.
}
}
You can use it in your main like that:
int main(void) // Note the void here when a function doesn't take any arguments
{
float num;
float result;
getfloat("Number", &num);
result = num * 1.2;
printf("Result: %.1f", result); // Print only one digit after the decimal point.
}
Sample output:
Number: x
Number: x12.45
Number: 12.75
Result: 15.3

Check user input in C with scanf()

Purpose:
If user input b is a float number prints floor(b), round(b), ceil(b).
Else prints scanf error: (%d)\n.
The instruction (provided by our teacher) has a code like this, which I don't understand.
Here's my code:
`
#include <stdio.h>
#include <math.h>
int main(void) {
float b;
printf("Eneter a float number");
int a=0;
a=5;
a=scanf("%d", &b);
if (a=0)
{
printf("scanf error: (%d)\n",a);
}
else
{
printf("%g %g %g",floor(b), round(b), ceil(b));
}
return 0
}
Mistake # 1
if (a=0) // condition will be always FALSE
must be
if (a==0)
or better
if (0 == a)
Mistake # 2
scanf("%d", &b); // when b is float
instead of
scanf("%f", &b);
UPDATE:
Actually, for case of checking results of scanf I personally prefer to use != with number of values entered with the last scanf. E.g. if two comma separated integers required to continue calculation snippet can be:
int x, y;
int check;
do{
printf("Enter x,y:");
check = scanf("%d,%d", &x, &y); // enter format is x,y
while(getchar()!='\n'); // clean the input buffer
}while(check != 2);
that loop will re-ask for input if check is not 2, i.e. if it is 0 (when even the first value is incorrect, e.g. abc,12) or if it is 1 (when user forgot comma or enter not a number after comma, e.g. 12,y
Code with corrections and comments - also available here - http://ideone.com/eqzRQe
#include <stdio.h>
#include <math.h>
int main(void) {
float b;
// printf("Eneter a float number");
printf("Enter a float number"); // Corrected typo
fflush(stdout); // Send the buffer to the console so the user can see it
int a=0;
// a=5; -- Not required
a=scanf("%f", &b); // See the manual page for reading floats
if (a==0) // Need comparison operator not assignemnt
{
printf("scanf error: (%d)\n",a); // A better error message could be placed here
}
else
{
printf("%g\n", b); // Just to check the input with ideone - debugging
printf("%g %g %g",floor(b), round(b), ceil(b));
}
return 0; // You need the semi-colon here
}
For VenuKant Sahu benefit
Return Value
These functions return the number of input items successfully matched
and assigned, which can be fewer than provided for, or even zero in
the event of an early matching failure.
The value EOF is returned if the end of input is reached before either
the first successful conversion or a matching failure occurs. EOF is
also returned if a read error occurs, in which case the error
indicator for the stream (see ferror(3)) is set, and errno is set
indicate the error.

While loop for only accepting integer value and exiting on any other input

I'm running this program in C to convert Fahrenheit to Celsius and need to accept only integer value from the user.
Please tell me how I can modify this?
int main() {
int x;
double y;
while(x>0) {
printf("Enter the temperature in Fahrenheit:");
scanf("%d", &x);
y=((x-32)/1.8)
printf("%f\n",y);
}
}
The reason your code does not work is that sometimes scanf does not read anything, so it does not modify x.
You know that scanf read something by checking its return value. It returns the number of "scanned" items. In this case, the number must be 1.
When scanf returns 0 instead, you should read and discard the data in the buffer. You do it by supplying %*[^\n] format specifier, which means "read and discard input up to '\n' character. The complete snippet that reads an int until success looks like this:
while (scanf("%d", &x) != 1) {
printf("Please enter a valid number:");
scanf("%*[^\n]");
}
Note: It goes without saying that you should fix your syntax error with the missing semicolon ; on the line that computes y.
You can use below code.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x;
double y;
char str1[5];
int num1,i;
bool yes = true;
while(x>0)
{
printf("Enter the temperature in Fahrenheit:");
scanf("%s",str1);
for(i=0;str1[i]!='\0';i++)
if(!(str1[i]>=48&&str1[i]<=56))
{
printf("The value is invalid \n");
yes = false;
}
num1 = atoi(str1);
if(yes == true)
{
printf("This Number is %d\n",num1);
y=((num1-32)/1.8);
printf("%f\n",y);
}
}
}

Finding if a Number if Prime or not In C

I was writing a C Program to find if a number is prime or not. Everytime I run it and enter a number, the value of the input changes. PLease point out the loopholes.
#include<stdio.h>
#include<conio.h>
int main()
{
int x;
int y;
y=getchar();
for(x=2;x<y;++x){
if(y%x != 0 && y!=x)
printf(" THE NUMBER %d is A PRIME \n", y);
else
printf(" \r THE NUMBER %d IS NOT A PRIME", y);
break;
}
}
I use the Code::Blocks IDE with GCC Compiler
As the name implies, getchar() gets a single character from standard input. For example, if you enter 3, the y gets the ASCII code of the character '3', which is obviously not what you want.
Try scanf:
scanf("%d", &y);
getchar returns the ASCII code of a single character. Consequently, your program picks up the ASCII code of the first character of the number you input and checks if it is prime.
Instead, you need to read an integer:
scanf("%d", &y);
The complete program:
#include<stdio.h>
#include<conio.h>
int main()
{
int x;
int y;
scanf("%d", &y);
for(x=2;x<y;++x){
if(y%x != 0 && y!=x)
printf(" THE NUMBER %d is A PRIME \n", y);
else {
printf(" \r THE NUMBER %d IS NOT A PRIME", y);
break;
}
}
}
Note: You can stop when x >= sqrt(y)
Well, you are calling getchar() which is used to input a single character and this is what happens in your case:
getchar() returns a character.
Character is then converted into integer when you store it in variable of type int.
Hence that integer contains the ASCII of input character i.e. 3 will be stored as 51 that is the reason input changes.
What you need to do is to input an integer instead of character. Try this:
scanf("%d", &y);
Hope this helps.
First answers are correct about input for y:
scanf("%d", &y);
Also, please note that you should loop until square root of x, and not more if your want to optimize your algorithm (I won't demonstrate here why, it's a mathematical property).
#include <stdio.h>
#include <math.h>
// ...
int x;
int x_max;
int y;
scanf("%d", &y);
x_max = (int)floor(sqrt(y));
for(x=2;x<=x_max;++x){
// ...

Resources