I am learning C I decided to make a file that would calculate the surface area and volume of a sphere once its radius was given by the user. However, when I tried compiling the program by typing in:
gcc Sphere.c -lm -o Sphere
and I enter the radius when I am prompted to, the SA and V output is always zero. What's going on here? I may be overlooking something simple. Here is my code:
#include <stdio.h>
#include <math.h>
double main()
{
double rad;
double sa, vol;
const double pi = 3.141592654;
printf("enter the radius of the sphere: \n");
scanf("%f", &rad);
vol = (4.0/3.0)* pi *(pow(rad,3));
sa = 4.0 * pi * (pow(rad,3));
printf("Volume of sphere is: %.3f", vol);
printf("\n Surface area of sphere is: %.3f", sa);
return 0;
}
You are using the wrong scanf() specifier.
The correct specifier for double is "%lf", and scanf() returns a value which you are ignoring causing possibly undefined behavior.
Also, main() does not have the signature you used, it returns a int, not a double or anything else, so your code would work if you fix at as follows
#include <stdio.h>
#include <math.h>
int main(void)
{
double rad;
double sa, vol;
const double pi = 3.141592654;
printf("enter the radius of the sphere: \n");
if (scanf("%lf", &rad) == 1)
{
vol = (4.0/3.0)* pi *(pow(rad,3));
sa = 4.0 * pi * (pow(rad,3));
printf("Volume of sphere is: %.3f", vol);
printf("\n Surface area of sphere is: %.3f", sa);
}
else
fprintf(stderr, "Invalid Input\n");
return 0;
}
Also, vim is a text editor, gcc is a compiler, and you are invoking the compiler with the least diagnostic that is possible, I recommend
gcc -Wall -Werror -g3 -O0 Sphere.c -o Sphere -lm
which will let you know about silly mistakes that you might somtimes make.
Edit:
As noticed by #A.S.H in the comments below, there is a mistake with the surface area formula it has to be
A = 4πr2
you have
A = 4πr3
which is wrong.
Related
This question already has answers here:
M_PI not available with gcc --std=c11 but with --std=gnu11?
(3 answers)
Closed 1 year ago.
I have the following code:
#define _USE_MATH_DEFINES
#include <math.h>
#include <stdio.h>
char r[15];
double radius;
double SphereVolume(double radius){
double volume;
volume = (4.0 / 3.0) * (M_PI) * (pow(radius, 3.0)); ///'identifier "M_PI" is undefined'
return (volume);
}
int main()
{
/* gets input from the user */
printf("What is the radius of the Sphere? ");
fgets(r, sizeof(r), stdin);
sscanf(r, "%lf", &radius);
printf("Volume of the sphere is %f", SphereVolume(radius));
return (0);
}
I can run it well with gcc by doing:
$> gcc -Wall -Werror -Wextra -o SphereVolume SphereVolume.c -lm
But VS Code isn't letting me even debugging the code. What is happening? do I have messed up settings?
I think I found the answer:
M_PI not available with gcc --std=c11 but with --std=gnu11?
Apparently M_PI is not defined in standard C
I can't figure out what im missing. I have a main method but it's still not building. Here's my code
#include <stdio.h>
// #include <conio.h>
int main(){
float length, width, area;
printf("Enter length of Rectangle\n");
scanf("%f", &length);
printf("Enter width of Rectangle\n");
scanf("%f", &width);
/* Area of Rectangle = Length X Width */
area = length * width;
printf("Area of Rectangle : %0.4f\n", area);
getch();
return 0;
}
Also im getting "make: *** [LabZero] Error 1" LabZero is the name of the project folder.
Thanks in advance
getch() is in curses.h, so you'll need to include it. In the code above you could just remove the getch() call, too.
The error message you posted is just make telling you the build failed; there should be more errors before that, from the compiler and/or linker, which should give you a better idea of why it failed.
I am writing a function in C with the below specifications:
float find_root(float a, float b, float c, float p, float q);
find_root takes the coefficients a,b,c of a quadratic equation and an interval (p, q). It will return the root of this equation in the given interval.
For example: find_root(1, -8, 15, 2, 4) should produce a root "close to" 3.0
I have written the below code, and I don't understand why it doesn't work:
#include<stdio.h>
#include<math.h>
main()
{
printf("Hello World");
}
float find_root(float a, float b, float c, float p, float q) {
float d,root1,root2;
d = b * b - 4 * a * c;
root1 = ( -b + sqrt(d)) / (2* a);
root2 = ( -b - sqrt(d)) / (2* a);
if (root1<=q || root1>=p)
{
return root1;
}
return root2;
}
Please let me know what the error is.
Your program doesn't work, because, you never called find_root() from your main().
find_root() is not suppossed to run all-by-itself. Your program statrs execution from main(). You need to call your sub-function from main() in order to make them execute.
Change your main to have a call to find_root(), something like below.
int main() //put proper signature
{
float anser = 0;
answer = find_root(1, -8, 15, 2, 4); //taken from the question
printf("The anser is %f\n", answer); //end with a \n, stdout is line buffered
return 0; //return some value, good practice
}
Then, compile the program like
gcc -o output yourfilename.c -lm
Apart from this, for the logical issue(s) in find_root() function, please follow the way suggested by Mr. #paxdiablo.
For that data, your two roots are 5 and 3. With p == 2 and q == 4:
if (root1<=q || root1>=p)
becomes:
if (5<=4 || 5>=2)
which is true, so you'll get 5.
The if condition you want is:
if ((p <= root1) && (root1 <= q))
as shown in the following program, that produces the correct 3:
#include<stdio.h>
#include<math.h>
float find_root (float a, float b, float c, float p, float q) {
float d,root1,root2;
d = b * b - 4 * a * c;
root1 = ( -b + sqrt(d)) / (2* a);
root2 = ( -b - sqrt(d)) / (2* a);
if ((p <= root1) && (root1 <= q))
return root1;
return root2;
}
int main (void) {
printf ("%f\n", find_root(1, -8, 15, 2, 4));
return 0;
}
That's the logic errors with your calculations of the roots.
Just keep in mind there are other issues with your code.
You need to ensure you actually call the function itself, your main as it stands does not.
It also wont produce a value within the p/q bounds, instead it will give you the first root if it's within those bounds, otherwise it'll give you the second root regardless of its value.
You may want to catch the situation where d is negative, since you don't want to take the square root of it:
a = 1000, b = 0, c = 1000: d <- -4,000,000
And, lastly, if your compiler is complaining about not being able to link sqrt (as per one of your comments), you'll probably find you can fix that by specifying the math library, something like:
gcc -o myprog myprog.c -lm
Your program starts at main by definition.
Your main function is not calling find_root but it should.
You need to compile with all warnings & debug info (gcc -Wall -Wextra -g) then use a debugger (gdb) to run your code step by step to understand the behavior of your program, so compile with
gcc -Wall -Wextra -g yoursource.c -lm -o yourbinary
or with
clang -Wall -Wextra -g yoursource.c -lm -o yourbinary
then learn how to use gdb (e.g. run gdb ./yourbinary ... and later ./yourbinary without a debugger)
Then you'll think and improve the source code and recompile it, and debug it again. And repeat that process till you are happy with your program.
BTW, you'll better end your printf format strings with \n or learn about fflush(3)
Don't forget to read the documentation of every function (like printf(3) ...) that you are calling.
You might want to give some arguments (thru your main(int argc, char**argv) ...) to your program. You could use atof(3) to convert them to a double
Read also about undefined behavior, which you should always avoid.
BTW, you can use any standard C compiler (and editor like emacs or gedit) for your homework, e.g. use gcc or clang on your Linux laptop (then use gdb ...). You don't need a specific seashell
Change this condition
if (root1<=q || root1>=p)
to
if (root1<=q && root1>=p)
otherwise if anyone of the conditions is satisfied, root1 will be returned and root2 will almost never be returned. Hope this fixes your problem.
This question already has answers here:
Undefined reference to sqrt (or other mathematical functions)
(5 answers)
Closed 5 years ago.
So I'm trying to make a program that calculates the quadratic formula, but when I try to compile the code, I get the following:"undefined reference to sqrt"
But I tried defining sqrt via math.h and 2 other times in the code.
I have attached my code
Any help would be greatly appreciated
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
double sqrt(double);
int main (void) {
double sqrt(double);
int a,b,c;
double discriminant,squarerootofdis,root1, root2;
printf("Please enter the coefficient of x^2:");
scanf("%d",&a);
printf("Please enter the coefficient of x:");
scanf("%d",&b);
printf("Please enter the integer value of the ploynomial:");
scanf("%d",&c);
if (a==0 && b==0)
{printf("This case is extremely degenerate");}
else if (a==0 && b!=0)
{root1=-c/b;
printf("Degenerate one real root: %lf\n",root1);}
else{
discriminant = ((b*b)-(4*a*c));
squarerootofdis = sqrt(discriminant);
root1 = (squarerootofdis-b)/(2*a);
root2 = (-squarerootofdis-b)/(2*a);
if (discriminant>0)
printf("Two real roots: %lf\n %lf\n", root1, root2);
else if (discriminant == 0)
printf("Degenerate one real root: %lf\n",root1);
else if (discriminant<0)
printf("Two complex roots: %lf\n %lf\n", root1, root2);
}
}
To use the sqrt function (or any function defined in math.h), you'll have to link the m library:
~$ gcc -lm yourcode.c -o program
Did you compile with -lm linked?
Header file will provide the decalration to the sqrt() function. To have the definition, you need to link with the math library consisting of the function definition.
Example:
gcc test.c -o output -lm
Please use the below command
gcc test.c -lmath
I am trying to write a program to approximate pi. It basically takes random points between 0.00 and 1.00 and compares them to the bound of a circle, and the ratio of points inside the circle to total points should approach pi (A very quick explanation, the specification goes in depth much more).
However, I am getting the following error when compiling with gcc:
Undefined first referenced
symbol in file
pow /var/tmp//cc6gSbfE.o
ld: fatal: symbol referencing errors. No output written to a.out
collect2: ld returned 1 exit status
What is happening with this? I've never seen this error before, and I don't know why it's coming up. Here is my code (though I haven't fully tested it since I can't get past the error):
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(void) {
float x, y;
float coordSquared;
float coordRoot;
float ratio;
int n;
int count;
int i;
printf("Enter number of points: ");
scanf("%d", &n);
srand(time(0));
for (i = 0; i < n; i++) {
x = rand();
y = rand();
coordSquared = pow(x, 2) + pow(y, 2);
coordRoot = pow(coordSquared, 0.5);
if ((x < coordRoot) && (y < coordRoot)) {
count++;
}
}
ratio = count / n;
ratio = ratio * 4;
printf("Pi is approximately %f", ratio);
return 0;
}
use -lm during compilation(or linking) to include math library.
Like this: gcc yourFile.c -o yourfile -lm
need to Link with -lm.
gcc test.c -o test -lm
The error is produced by the linker, ld. It is telling you that the symbol pow cannot be found (is undefined in all the object files handled by the linker). The solution is to include the library which includes the implementation of the pow() function, libm (m for math). [1] Add the -lm switch to your compiler command line invocation (after all the source file specifications) to do so, e.g.
gcc -o a.out source.c -lm
[1] Alternatively, you could have your own implementation of pow() in a separate translation unit or a library, but you would still have to tell the compiler/linker where to find it.