Floating point math in c getting random numbers [closed] - c

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm doing a exercise from C primer plus that involves working with floats, I can't get the result to also be a float. I got it to read in the input fine (as far as I can tell) but the problem must be in the formula line. Can anyone tell me what I'm doing wrong?
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
float inp1, inp2;
float result;
result = (inp1 - inp2) / (inp1 * inp2); /* formula */
printf("enter two values\n");
scanf("%f %f", &inp1, &inp2);
printf("(%.3f - %.3f) / (%.3f * %.3f)\n", inp1, inp2, inp1, inp2);
printf("%f\n", result);
}
The output is giving some random number (I don't know what it's called), for example with an input of 1.255 and 1.023 I get an output of 2656044210243861500000000000000000000.000000 or something similar. The second to last printf displays the input correctly.
What am I doing wrong?
I've tried this, but I don't really get how cast operators work.
result = ((float)inp1 - (float)inp2) / ((float)inp1 * (float)inp2); //formula
and
result = (float)(inp1 - inp2) / (inp1 * inp2);

result = (inp1 - inp2) / (inp1 * inp2); /* formula */
printf("enter two values\n");
scanf("%f %f", &inp1, &inp2);
Well, what about putting scanf call before result = ...; assignment statement?

result = (inp1 - inp2) / (inp1 * inp2); /* formula */
printf("enter two values\n");
scanf("%f %f", &inp1, &inp2);
That's not how things work in a language like C; you don't define a formula for result that's automatically computed when you read your inputs. Rather, you first read your inputs, and then you compute the value and assign it to result:
printf("enter two values\n");
scanf("%f %f", &inp1, &inp2);
result = (inp1 - inp2) / (inp1 * inp2); /* computation and assignment */
C is an imperative language, meaning you have to explicitly list out the instructions for it to follow, including those for any mathematical computations.

The analogy of math formulas in programming languages is functions (without side effects). That way, you can define formulas before the code itself. For instance:
#include <stdio.h>
#include <stdlib.h>
float formula(float inp1, float inp2)
{
return (inp1 - inp2) / (inp1 * inp2);
}
int main(void)
{
float inp1, inp2;
printf("enter two values\n");
scanf("%f %f", &inp1, &inp2);
printf("(%.3f - %.3f) / (%.3f * %.3f)\n", inp1, inp2, inp1, inp2);
printf("%f\n", formula(inp1, inp2));
return 0;
}

Related

need to put integer number but it says lvalue required as left operand of assignment [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 months ago.
Improve this question
Edited: fixed some typos, also add more context
So I tried to put this code:
#include <stdio.h>
int main() {
float ps, ls, ms, es;
printf("Enter the project score: ");
scanf("%d", &ps);
printf("Enter the long exam score: ");
scanf("%d", &ls);
printf("Enter the midterm exam score: ");
scanf("%d", &ms);
90 = (ps * 0.15) + (ls * 0.2) + (ms * 0.25) * (es * 0.4);
printf("Final exam score needed: %d", es);
return 0;
}
As I want this equation 90=85(.15)+88(.2)+92(.25)+x(.4)
but it states that "lvalue required as left operand of assignment"
As others point out you need to use %f to read in float.
But here's an example that solves your equation:
Given the scores of the Project, Long Exam and Mid-term what score in the Final Exam is required for a weighted average of 90.
C is an 'imperative' procedural programming language.
You need to specify how to derive the es value.
It can't be expected to solve your equation.
The = means "assign to the variable on the left the value on the right".
It's not a statement of equality or even a logical test. It's an act of assigning a value into a variable.
I'm labouring the point because a 'breakthrough' understanding in programming is that equals "=" doesn't always mean what it does in Maths. In fact rarely does!
If you try 90, 90 and 90 below it will say 90 (which makes sense).
If you try 80, 85 and 90 you need a final score of 93.125.
This code does a back check to show the value calculated gives the right weighted score.
#include <stdio.h>
int main() {
float ps, ls, ms, es;
printf("Enter the project score: ");
scanf("%f", &ps);
printf("Enter the long exam score: ");
scanf("%f", &ls);
printf("Enter the midterm exam score: ");
scanf("%f", &ms);
printf("\nps=%f ls=%f ms=%f\n",ps,ls,ms);
es=(90-(ps * 0.15) - (ls * 0.2) - (ms * 0.25) )/0.4;
printf("Final exam score needed: %f\n", es);
float check=ps*0.15+ls*0.2+ms*0.25+es*0.4;
printf("Giving final score of %f\n",check);
return 0;
}
Typical Output:
Enter the project score: Enter the long exam score: Enter the midterm exam score:
ps=80.000000 ls=85.000000 ms=95.000000
Final exam score needed: 93.125000
Giving final score of 90.000000
For starters you declared variables as having the type float
float ps, ls, ms, es;
So to enter values to the variables you have to use the conversion specifier f instead of d like
printf("Enter the project score: ");
scanf("%f", &ps);
This statement
90 = (ps * 0.15) + (ls * 0.2) + (ms * 0.25) * (es * 0.4);
does not make a sense. You may not change an integer constant. Also it is unclear why there is used the magic number 90.
As in the next statement you are trying to output the value of the variable es again using the invalid conversion specifier d instead of f then it seems you mean
es = (ps * 0.15) + (ls * 0.2) + (ms * 0.25) * (es * 0.4);
printf("Final exam score needed: %f\n", es);
However pay into account that the variable es was not initialized. So the program will have undefined behavior.
Maybe you mean something like (though it is difficult to say what actually you mean)
es = (ps * 0.15) + (ls * 0.2) + (ms * 0.25);
es *= 0.4;
You have
90=85(.15)+88(.2)+92(.25)+x(.4)
This should be
// solve equation for x
float x = (90 - (85*(.15)+88*(.2)+92*(.25))) / .4;
printf("Final exam score needed: %f\n", x);

Why my C program can't read data from file using "<" character [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
I am writing a demo C application in batch mode, which will try to read from a file as input.
The command is : metric <mydata
The C source file is:
/* Converts distances from miles to kilometers. */
#include <stdio.h> /* printf, scanf definitions */
#define KMS_PER_MILE 1.609 /* conversion constants */
int main(void)
{
double miles, /* distance in miles */
kms; /* equivalent distance in kilometers */
/* Get and echo the distance in miles. */
scanf("1f", &miles);
printf("The distance in miles is %.2f.\n", miles);
/* Convert the distance to kilometers. */
kms = KMS_PER_MILE * miles;
/* Display the distance in kilometers. */
printf("That equals %.2f kilometers.\n", kms);
return (0);
}
The file "mydata" contains simply an integer 100
When I run the command metric <mydata. The output is:
The distance in miles is 0.00.
That equals 0.00 kilometers.
Is there any idea what's wrong?
You misread the doc: instead of scanf("1f", &miles); you should write:
scanf("%lf", &miles);
Testing the return value of scanf() avoids undefined behavior when the conversion fails and would have helped detect this error. Enabling all warnings in your compiler (gcc -Wall -Wextra -Werror) is also recommended to avoid silly mistakes.
Here is a modified version:
/* Converts distances from miles to kilometers. */
#include <stdio.h> /* printf, scanf definitions */
#define KMS_PER_MILE 1.609 /* conversion constants */
int main(void) {
double miles; /* distance in miles */
double kms; /* equivalent distance in kilometers */
/* Get and echo the distance in miles. */
if (scanf("%lf", &miles) != 1) {
fprintf(stderr, "invalid input\n");
return 1;
}
printf("The distance in miles is %.2f.\n", miles);
/* Convert the distance to kilometers. */
kms = KMS_PER_MILE * miles;
/* Display the distance in kilometers. */
printf("That equals %.2f kilometers.\n", kms);
return 0;
}

Code is skipping a command in the program. (C) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
Brief Description of Code: It's a quadratic equation calculator. It helps you find the roots of an equation.
Code:
#include <stdio.h>
#include <math.h>
main(){
int a, b, c, real;
float root1, root2, img, dis;
char solve;
printf("Do you want to solve an equation (y/n): ");//Ask user if they want to solve an equation
scanf("%c", &solve);
if(solve == 'n'){//Terminate program
return 0;
}
if(solve == 'y'){//Code for calculation
printf("\nInput the number");
printf("\n````````````````");
printf("\nA: ");//Store number for a, b, c for the quadratic formula
scanf("%d", &a);
printf("\nB: ");
scanf("%d", &b);
printf("\nC: ");
scanf("%d", &c);
dis = (b*b) - (4*a*c);//calculation for the discriminent
//printf("%f", dis); Check the discriminant value
if(dis > 0){//Calculation for the real root
root1 = ((b*-1) + sqrt(dis))/(2*a);
root2 = ((b*-1) - sqrt(dis))/(2*a);
printf("\nRoot 1: %.2f", root1);
printf("\nRoot 2: %.2f", root2);
return 0;
}
if(dis = 0){//Calculation for no discriminent
root1 = (b*-1)/(2*a);
printf("\nRoot 1 and 2: %.2f", root1);
return 0;
}
if(dis < 0){//Calculation for complex root
dis = dis * -1;
//printf("\n%f", dis); !!!Testing to see why the code isn't functioning!!! It skipped this
root1 = (b*-1)/(2*a);
img = (sqrt(dis))/(2*a);
printf("Root 1 and 2: %.2f ± %.2f", root1, img);
return 0;
}
}
}
Problem: It works perfectly fine if the discriminant is greater than zero. But when it's equal to or less than zero, it skips everything in the code for some reason. I'm having trouble finding the error. I put in printf statement to see what is the value of the discriminant and I kept a printf statement in the if statement to see if it will printf anything, but it skipped that.
Output I got:
gcc version 4.6.3
Do you want to solve an equation (y/n): y
Input the number
````````````````
A: 1
B: 2
C: 5 //It ends here
Output I want:
gcc version 4.6.3
Do you want to solve an equation (y/n): y
Input the number
````````````````
A: 1
B: 2
C: 5
Root 1 and 2: -1±2i
If you look at you if statement for dis = 0, it should:
if(dis == 0)
That should fix all your problems. Nice job with the code. Just a beginner mistake.
You're using the operator = when you want the operator ==.
a == b checks if 2 numbers are equal, while a = b sets the first to the value of the second.
In other words, change dis = 0 to dis == 0.

Error must be a modifiable lvalue [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I'm trying to make a simple currency converter using C, but for some reason it keeps giving me the error "error must be a modifiable lvalue".
I have checked up my code, and I don't see any problems with it. Any help?
#include <stdio.h>
#include <stdlib.h>
void main(){
float jod_usd=1.41, usd_jod=0.71, jod_eur=1.26, eur_jod=0.8, currency;
char ic;
int f;
printf("Enter the number of your conversion option to continue...\n1- Convert from JOD\n2- Convert to JOD\n");
scanf("%d",&f);
printf("Enter the character of your second currency to continue...\nU - - USD\nE - - EUR\n");
scanf("%c",&ic);
printf("Enter your amount:\n");
scanf("%f",&currency);
if(f==1&&(ic='U'||ic='u')){
printf("%.2f JOD - - %.2f USD\n",currency,(currency*jod_usd));
}
if(f==1&&(ic='E'||ic='e')){
printf("%.2f JOD - - %.2f EUR\n",currency,(currency*jod_eur));
}
if(f==0&&(ic='E'||ic='e')){
printf("%.2f EUR - - %.2f JOD\n",currency,(currency*eur_jod));
}
if(f==0&&(ic='U'||ic='u')){
printf("%.2f USD - - %.2f JOD\n",currency,(currency*usd_jod));
}
system("pause");
}
TL;DR The mistake of using = instead of == caused this.
First, you're changing the value of ic unwantedly.
Second, due to operator precedence,
(ic='U'||ic='u')
is the same as
((ic='U'||ic) = 'u')
where, the result of (ic='U'||ic) is not an lvalue.
Are you sure it is not just a simple bug? You usually don't assign in a condition. If I fix that, then you get some program flow:
Enter the number of your conversion option to continue...
1- Convert from JOD
2- Convert to JOD
1
Enter the character of your second currency to continue...
U - - USD
E - - EUR
Enter your amount:
Code
#include <stdio.h>
#include <stdlib.h>
void main(){
float jod_usd=1.41, usd_jod=0.71, jod_eur=1.26, eur_jod=0.8, currency;
char ic;
int f;
printf("Enter the number of your conversion option to continue...\n1- Convert from JOD\n2- Convert to JOD\n");
scanf("%d",&f);
printf("Enter the character of your second currency to continue...\nU - - USD\nE - - EUR\n");
scanf("%c",&ic);
printf("Enter your amount:\n");
scanf("%f",&currency);
if(f==1 && (ic=='U' || ic=='u')){
printf("%.2f JOD - - %.2f USD\n",currency,(currency*jod_usd));
}
if(f==1&&(ic=='E'||ic=='e')){
printf("%.2f JOD - - %.2f EUR\n",currency,(currency*jod_eur));
}
if(f==0&&(ic=='E'||ic=='e')){
printf("%.2f EUR - - %.2f JOD\n",currency,(currency*eur_jod));
}
if(f==0&&(ic=='U'||ic=='u')){
printf("%.2f USD - - %.2f JOD\n",currency,(currency*usd_jod));
}
system("pause");
}

Adding float values in c [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Why does f is 0.0 even after adding 0.1?
#include <stdio.h>
int main()
{
float f=0.0f;
f = f + 0.1f;
printf("f %f \n",&f);
return 0;
}
Sorry for that I messed up with original question
Why these two values are not ? Is this because of precision.
Sorry I have to ask this question here because I'm blocked I can't ask more questions
#include <stdio.h>
int main()
{
float f=0.0f;
int i;
for(i=0;i<10;i++)
{f = f + 0.1f; }
if(f == 1.0f)
printf("f is 1.0 \n");
else
printf("f %f is NOT 1.0\n",f);
return 0;
}
printf("f %f \n",f);
Gives correct output. See here-https://ideone.com/158Zbv
To print address printf(" %p \n",&f); will do it .
Where as your printf statement will give undefined behaviour.
About your second code -
You can re-write your if condition like this -
if(f>0.99f && f<1.01f)
So that it gives you correct output- https://ideone.com/kARx3A
EDIT
While adding in your program value of f is not exactly 1.0f but it may have some different value ,when we see its value with more decimal places it is bit different than 1.0f that's why your code always go to else part .
See here what value f has with every iteration-https://ideone.com/wJ7u1R
you are printing address of variable f by using & operator, remove this & operator.

Resources