square of a float number in C
49,801
Solution 1
Move the declaration of square()
out of the function and make sure the prototype matches:
float square(float b); // Make sure this matches the definition.
int main()
{
float a,y;
scanf("%f", &a);
y = square( a );
printf("%f %f ",a ,y);
}
float square(float b)
{
float z;
z = b*b;
printf("%f %f",z ,b);
return(z);
}
As for why it "worked" for int
, you'll have to show us the exact code you used for that case.
Solution 2
You're just missing the argument in the prototype you gave. You had
float square();
When it should be
float square(float);
You don't need to move it outside the function, but you do need to make sure the prototype has the same signature (return type, name, and parameter count/types) as the function that you define later.
Comments
-
Sudhanshu Gupta almost 2 years
I have written a code in C which works fine for int but when I try to do this with float it is showing error what can i do to make it correct.
#include<stdio.h> int main() { float a,y; float square(); scanf("%f", &a); y = square( a ); printf("%f %f ",a ,y); } float square(float b) { float z; z = b*b; printf("%f %f",z ,b); return(z); }
error:
return.c:12: error: conflicting types for 'square' return.c:13: note: an argument type that has a default promotion can't match an empty parameter name list declaration return.c:6: note: previous declaration of 'square' was here
-
Seth Carnegie over 12 yearsC does something special for when you call functions that haven't been declared yet. It assumes that the arguments and return type is
int
or something, I can't remember exactly. -
Mysticial over 12 yearsYeah, I'm aware of that. But I'm not sure on the exact behavior since I never use that functionality... Same applies to functions inside functions - it's an area I avoid.
-
Sudhanshu Gupta over 12 yearsThanks both of both answers worked , I think C takes "int" if we have not declared type . Is that true what i am thinking of .
-
Mysticial over 12 yearsYes, C does take a default int when no type is specified. However, this is depreciated and it's recommended to always specify the type. So my guess is that the default
int
allowed your initial case to work. -
Mysticial over 12 yearsInteresting, I didn't know you could leave the declaration inside the function. +1
-
Seth Carnegie over 12 years@Mysticial that's where the annoying thing comes from where you cannot value-initialise a variable (or is it default initialise?) whose constructor takes no arguments:
MyClass m;
works butMyClass m();
doesn't because it's a function prototype. (Same for builtin types too.)