I'm very new to coding. I'm trying to make a simple math equation making use of float, using this code:
#include <stdio.h>
#include <math.h>
int car() {
int r1;
int m1;
int m2;
float lift_a_car(const int r1, const int m1, const int m2);
lift_a_car = r1 (2 * m1 / (m1 m2));
printf("%.4f\n", lift_a_car(2, 80, 1400));
return 0;
}
Whenever I run it, I get this error:
arrays.c:12:12: error: lvalue required as left operand of assignment
12 | lift_a_car = r1 (2 * m1 / (m1 m2));
I couldn't find a good explanation for this error anywhere. Can someone please explain this error to me? And is there any way to simplify/improve this code overall?
CodePudding user response:
lift_a_car
is a function and you cannot assign to a function in C. If you wanted to define a function, you should specify a function body using curly braces:
float lift_a_car(const int r1, const int m1, const int m2)
{
return r1 (2 * m1 / (m1 m2));
}
Note that you cannot define a function inside of another function in C, so your lift_a_car
function must be defined outside and before your car
function.
CodePudding user response:
Try something like that:
#include <stdio.h>
#include <math.h>
// functions shall be defined here
float lift_a_car(int r1, int m1, int m2)
{
// note to get a float result, you need to cast to float
return (r1 (2 * (float)m1 / (m1 m2)));
}
int main() {
// Here you can call the function
printf("%.4f\n", lift_a_car(2, 80, 1400));
return 0;
}
CodePudding user response:
It seems like you want to create a function lift_a_car
. It must be outside of int car
as nested functions are not supported. Functions must be top-level entities in C, not within any scope ({}
). (In your code, lift_a_car
is inside car
). And the name of the entry-point function must be main
. Since your car
function returns 0
, it seems like you are trying to use car
instead of the name main
:
#include <stdio.h>
#include <math.h>
float lift_a_car(const int r1, const int m1, const int m2)
{
float result = r1 (2 * m1 / (m1 m2));
return result;
}
int main()
{
int r1 = 2;
int m1 = 80;
int m2 = 1400;
printf("%.4f\n", lift_a_car(r1, m1, m2));
return 0;
}
Also, since you are performing division with two integers, the decimal points will be truncated, so cast one of the values first to float
to retain the decimal points:
float lift_a_car(const int r1, const int m1, const int m2)
{
float result = r1 ((float) 2 * m1 / (m1 m2));
return result;
}
We could try to help more if you provide more details about what you are trying to do.