I am working on a problem in my textbook and I need to make a triangle angle calculator Im used to java but Im not 100% on C yet, I don't understand the logic in it.
#include <stdio.h>
static float angleB;
static float angleA;
float remainingAngle(float answer)
{
float answer= angleA+angleB;
//redefinition of answer
return 0;
}
//CANT TOUCH FROM HERE TO END
int main(int argc, const char * argv[]) {
float angleA = 30.0;
float angleB = 60.0;
float angleC = remainingAngle(angleA,angleB);
// to many arguments to function call (referring to angleC)
printf("the third angle is %.2f\n",angleC);
return 0;
} //END CANT TOUCH
I don't know what to do here.
In your function definition
float remainingAngle(float answer)
the function remainingAngle() accepts one parameter.
OTOH, in your function call
remainingAngle(angleA,angleB);
you're passing two arguments.
The supplied argument number and type should match with the parameter list in function definition.
That said, your code is wrong.
Point 1. Your local variables will shadow the global ones. Maybe that's not what you want. Change
float angleA = 30.0;
float angleB = 60.0;
to
angleA = 30.0;
angleB = 60.0;
Point 2. The function
float remainingAngle(float answer)
{
float answer= angleA+angleB;
//redefinition of answer
return 0;
}
is logically wrong. It should rather be
float remainingAngle(void)
{
float answer= angleA+angleB;
return answer;
}
and should be called like
float angleC = remainingAngle();
AFTER EDIT:
as per your requirement, you can do
float remainingAngle(float angleA, float angleB)
{
float answer= angleA+angleB;
return answer;
}
However, this makes the global variables useless.
In addition to Souravs answer you could also do the following:
float remainingAngle(float angA, float angB)
{
float answer = angA + angB;
return answer;
}
So your call will stay the same.
And for the logical side, what you do is:
You pass two arguments (value of angleA and value of angleB) to the function remainingAngle. There you do the calculation and return the result (answer).
The design of your function isn't good:
static float angleB;
static float angleA;
float remainingAngle(float answer)
{
float answer= angleA+angleB;
//redefinition of answer
return 0;
}
What do I do?
There's no point is passing in the answer; the answer is what you want to receive. (There's also no point in passing "space" for the answer. The anser is a float, a scalar variable. Just pass that around.) Remove the answer argument.
You redefine answer as local variable. After removing the argument of the same name, that redefinition goes away. But in that case you should return answer instead of 0. You could even do without the intermediary variable answer and return the result expression. So: Return the desired expression
The answer depends on two global variables. The function should work on two angles that you pass as arguments. Provide two angle arguments to your function and remove the global variables.
And finally, the sum of the three angles in a triangle is 180°, so your remaining angle calculation is wrong.
Putting all that together:
float remainingAngle(float a, float b)
{
return 180.0f - a - b;
}
and call it like this:
float angleC = remainingAngle(angleA, angleB);
Im used to java
I'm not too familiar with Java, but I don't think functios on scalars like this one are fundamentally different in C and Java.
Related
This question already has answers here:
Getting "conflicting types for function" in C, why?
(11 answers)
Closed 5 years ago.
float pie = 3.14;
int main()
{
float r,res;
printf("Enter radius value\n");
scanf("%f", &r);
res=area( r );
printf("Area = %f\n",res);
//printf("Circumference = %f\n", circum( r ));
}
float area( float r )
{
return pie * r * r;
}
I'm getting error as conflicting types for 'area' and previous implicit declaration of 'area' was here,But this code works fine if i changed to integer
In IDE it works fine if i changed that code to integer float pie = 3.14;
int main() {
int r,res;
printf("Enter radius value\n");
scanf("%d", &r); res=area( r );
printf("Area = %d\n",res);
}
int area( int r )
{
return pie * r * r;
}
without declaration it works fine for integer but for floating point numbers i am getting error why?
C allows implicit function declaration, so because you didn't give an explicit function declaration prior to calling it for the first time, it's implicitly declared with this prototype:
int area(); // Implicit arguments
And later when you give a real declaration, they're conflict.
If you want the function to return an actual floating point number, give a forward declaration:
float area(float);
Add the above line before int main() and the problam is solved.
By the way, implicit function declaration is removed as of C11 standard (ISO/IEC 9899:2011).
Whenever you are using a common term or a variable all over the program
like you did here
float pie = 3.14
write this instead
#define pie 3.14 //this is a macro
and coming to your error ,
whenever you are using a function, you have to provide a explicit declaration of it or in other words prototype of it.
Type this on top of your C file
float area(float r)
or
float area(float)
And if you feel lazy then use your function before your main function instead using it after you main function.
You should do function call after function defination.Otherwise declar function in header file and use it.
I have recently stumbled on this curious thought while handling a C code.
I have written a function which returns a double and takes in as argument the pointer to a function and a certain number of parameters, namely
double template_1(double (*)(double),...);
this function correctly identifies a certain property of a real function
double f(double );
represented as a pointer in template_1, in order to maketemplate_1 valid for every real function I might plug-in.
Now I had to write another function, let it be:
double derivative(double (*)(double),double);
double derivative(double (*f)(double),double x){
double epsilon = ...;
return ( f(x+epsilon)-f(x-epsilon) )/(2.0*epsilon);
}
again with f in the argument to make it work for every f.
My question is: since I would like to use derivative in template_1 without modifying it, is it possible to write a function which takes derivative and spits out something that has the form of double (*)(double ) ?
My idea was to define typedef double (*real_function)(double);
and then to define
real_function g(double (*derivative)(double (*)(double),double ) )
which I'd like it to spit out something like: double derivative_2(double x); so that I could define something like g(derivative) = double (*h)( double); directly in template_1 argument
unfortunately I don't have the faintest idea of how to make this work, or even if it can work.
There are a couple ways to do anonymous functions in C. As the comments said, they aren't portable. But depending on the use case you may find this useful: Anonymous functions using GCC statement expressions
A couple of people have seemed to have similar issues, not sure how portable they are but they may be resourceful:
https://github.com/graphitemaster/lambdapp
https://github.com/Leushenko/C99-Lambda
Basically, if there's a way to architect your program in a way that doesn't require anonymous functions, then do it that way. If you have no other option, then I would give one of these a shot.
Warning: I am a C++ developer with little C knowledge so everything that follows is likely unidiomatic C.
As KerrekSB said, you would need to carry some state with your function. This is not possible with raw functions but you can define a struct that carries the state and add a function that works with this struct. This obviously has the drawback of losing the nice function call syntax. I whipped up an example:
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
typedef double (*raw_fptr)(double);
struct real_function;
typedef double (*evaluate_function)(struct real_function*, double);
struct real_function {
evaluate_function evaluate;
};
typedef struct real_function real_function;
double evaluate(real_function *f, double x) {
if(f) {
return f->evaluate(f, x);
}
return NAN;
}
struct raw_real_function {
real_function real_function_base;
raw_fptr raw_function;
};
typedef struct raw_real_function raw_real_function;
double evaluate_raw_real_function(real_function *f_base, double x) {
if(f_base) {
raw_real_function *f = (raw_real_function*)f_base;
return f->raw_function(x);
}
return NAN;
}
raw_real_function make_raw_real_function(raw_fptr function) {
raw_real_function result;
result.raw_function = function;
result.real_function_base.evaluate = evaluate_raw_real_function;
return result;
}
struct derive_real_function {
real_function real_function_base;
real_function *function_to_derive;
};
typedef struct derive_real_function derive_real_function;
double derive(real_function *f_base, double x) {
derive_real_function *f = (derive_real_function*)f_base;
double epsilon = 1e-3;
double upper = evaluate(f->function_to_derive, x+epsilon);
double lower = evaluate(f->function_to_derive, x-epsilon);
double result = (upper - lower)/(2.0*epsilon);
return result;
}
derive_real_function make_derivative(real_function * function_to_derive) {
derive_real_function result;
result.real_function_base.evaluate = derive;
result.function_to_derive = function_to_derive;
return result;
}
double x_cubed(double x) {
return x * x * x;
}
int main(int argc, char **argv) {
raw_real_function x_cubed_wrapped = make_raw_real_function(x_cubed);
derive_real_function derived = make_derivative(&x_cubed_wrapped.real_function_base);
derive_real_function derived_twice = make_derivative(&derived.real_function_base);
double x = atof(argv[1]);
double derivative = evaluate(&derived.real_function_base, x);
double second_derivative = evaluate(&derived_twice.real_function_base, x);
printf("derivative of x^3 at %f = %f\n", x, derivative);
printf("second derivative of x^3 at %f = %f\n", x, second_derivative);
return 0;
}
See (a slight variaton, due to input limitations) running here.
How does it work? I faked some inheritance with the structs real_function, raw_real_function and derive_real_function to generate virtual function calls. The struct real_function serves as the container of a virtual function table consisting of only the entry evaluate. This function pointer points to the "derived" structs' relevant evaluate function:
raw_real_function instances point to evaluate_raw_real_function (as initialized in make_raw_real_function. derive_real_function instances point evaluate to derive (as initialized in make_derivative).
When calling evaluate on the real_function_base member, it will call the associated evaluation function, which casts the real_function* to it's associated struct pointer and does what is needed with that information.
Since everything is just a real_function*, we can chain them at will but need to convert "normal" functions into the real_function format, that's what make_raw_real_function does.
If you have a function my_fancy_function:
double my_fancy_function (double x) { return sin(x) + cos(x); }
Then, you can use a helper macro that creates the derived function for you.
#define DEFINE_DERIVATIVE_OF(FUNC) \
double derivative_of_ ## FUNC (double x) { \
return derivative(FUNC, x); \
}
DEFINE_DERIVATIVE_OF(my_fancy_function)
You then pass this newly defined function to your template.
template_1(derivative_of_my_fancy_function, x, y, z);
I am trying to return a float value and assign it to a float variable, but the value of the new float is different from the returned one.
float getVoltageReading() {
return 1.2f;
}
void updateUIReadings(uint8_t menuID) {
float integerReading = getVoltageReading(); // digital voltage
}
In debugger I see that getVoltageReading return 1.2, but the integerReading is assigned to be 1.06703091e+009
Why is that?
You are calling the getVoltageReading function without an active prototype in scope, which means it is assuming that it will return an int. It looks like, from the way your question is organised, that it is in scope, but I can assure you it's not.
You can see that with the following two files, testprog1.c:
#include <stdio.h>
//float getVoltageReading(void);
int main(void) {
float integerReading = getVoltageReading ();
printf("%e\n", integerReading);
return 0;
}
and testprog2.c:
float getVoltageReading(void) {
return 1.2f;
}
When these are compiled and linked together, the output is:
1.067031e+09
because the float value being returned from getVoltageReading() is being interpreted as an int. If you uncomment the prototype in testprog1.c, it works fine because it interprets the float value as a float:
1.200000e+00
While compiling this code in the terminal, I am getting an error saying :
newfile1.c:17: error: conflicting types for ‘average’
newfile1.c:2: note: previous declaration of ‘average’ was here
I don't see what is wrong with the code. Could someone help me out?
enter code here
#include<stdio.h>
float average(float);
int main()
{
float marks[4],avg;
int i;
printf("Please enter your marks\n");
for(i=0;i<=3;i++)
{
scanf("%d",&marks[i]);
}
avg = average(marks[4]);
printf("The average marks value is %f",avg);
return 0;
}
float average(float a[4])
{
int i,sum;
float avg_m;
for(i=0;i<=3;i++)
{
sum=sum+a[i];
}
avg_m=sum/3;
return avg_m;
}
Replace
float average(float);
with
float average(float[]);
The function declaration and definition are not matching.
Then call the function like this:
avg = average(marks);
Change line in your file
float average(float);
to
float average(float []);
You have declared the function to take one float instead you want array of floats.
Also, while calling it in main, change to
avg = average(marks);
float average(float);
expects a float variable . You need to pass an array , so add
float average(float[]);. Error happened since your function declaration and definition not matching.
in your main, you should call avg = average(marks); to pass the array to function avg = average(marks[4]); will pass a single variable.
In the prototype of average, you have given float as argument type so compiler is expecting a single float value as argument. If you want to pass an array of values, you have to declare your prototype like this:
float average(float input_marks[]);
You can't give length of an array argument in a prototype or definition. You have to pass array length as a separate argument. So your prototype should look something like
float average(float a[], int a_length);
Your function average takes one float as argument, hence the declaration should be floa avaerage(float). If you do float average(float a[4]) you are telling compiler that your function takes an array of 4 floats as argument.
Given the two code examples which is preferred? In the first the return variable is defined as a local variable. In the second the return variable is passed by the caller. Are you allowed to define a function and return a variable that was passed to it? I's this simply a preference of one or the other? is there a performance difference?
float compute_diam(float circumference, float pi) {
float rval;
/* Circumference = pi * diameter, so
diameter = circumference / pi */
rval = circumference / pi;
return rval;
}
and
float compute_diam(float circumference, float pi, float rval) {
/* Circumference = pi * diameter, so
diameter = circumference / pi */
rval = circumference / pi;
return rval;
}
Thanks
I think in these two cases the 1st one is better for following reason
1. Due to performance as you are passing variable by value it is once created where ever you declare rval, and once when you pass that rval to function with value of first rval copied to second.
instead if you want to pass variable in this manner pass it by reference as
void main()
{
float result;
compute_diam(2.1, 3.14, &result);
}
void compute_diam(float circumference, float pi, float* rval) {
/* Circumference = pi * diameter, so
diameter = circumference / pi */
*rval = circumference / pi;
}
after completion of the function variable result will hold the value of diameter.
Sometime you may want to pass the reference of the variable and then fill it will appropriate value or return codes.
However the second definition does not make any sense.
int foo()
{
int a=6;
return a; // This is ok
}
int foo(int a)
{
a = 5;
return a; // Calling function cant access the value 5 in the parameter
//passed, it has to hold it in another variable
}
void foo(int* a)
{
*a=5;
return; // Here you can return and still access the value 5 in the calling
//function with the variable passed to it
}
Hence i am assuming you want to decide between first and third method and i would say its implementation specific. If you want to pass a sequence of return values(read array,structures) you can use the second.
I'd prefer the first as the second doesn't make any sense. The second you're not passing in a reference or a pointer to the rval so you're just assigning to a local variable (as you are in the first, yet it's created differently) and then returning a copy of that variable to the caller. Note that you're not saving the value in the rval passed TO the function, you're saving it in the local rval created BY the function via the parameter list.
Even if the second example was passing a reference to rval, I would still prefer the first as rval is a regular type and is easily and efficiently copied. I also find:
float diameter = compute_diam(circumference, pi);
much more readable and concise than:
float diameter = 0;
compute_diam(circumference, pi, diameter);
If you were putting data into a large object/struct, then passing a reference into the function would make more sense. A compiler many times can optimize out the copy associated with a function that incurs a copy for the return value, so I would probably stay with option 1 until you find through the use of a profiler that it needs to be optimized to something like the 2nd version.
Also, you could remove pi from the argument list and make a static const float PI = 3.14xxxx; inside the function body.
Typically, the only reasons to store the return value at an address passed as a parameter are:
You need to return multiple values.
You need to return a structure.
You need to use the return value of the function to return errors.
The function is designed to modify one of the parameters.
If you look through the standard C library, or most any API, you'll find few instances of return values stored at an address passed as a parameter.
This let me think that you don't understand what a return value is or how arguments are given to a function.
In your second example, you will not modify the rval that you are giving at function call, but a copy of it. And you will then return the value of rval.
Your second example is then "wrong" (from a logic point of view).
What you were trying to do is
void compute_diam(float circumference, float pi, float& rval) {
/* Circumference = pi * diameter, so
diameter = circumference / pi */
rval = circumference / pi;
}
Edit: Correction, the above is only C++, in C you would do the following
void compute_diam(float circumference, float pi, float* rval) {
/* Circumference = pi * diameter, so
diameter = circumference / pi */
*rval = circumference / pi;
}
Where rval is given by reference and where the function doesn't return anything (void).
But this should be avoided in that simple case, the interface is more clear if the function return a value.
Edit:
To convince you that your second example is ill formed, think about the following:
float my_result = compute_diam(2.0, 3.14, 'why and what would I put here ? my_result ? ')