What is wrong with my square root code? - c

What is wrong with this code? I am learning both Python and C at the same time. Similar code on Python works fine but I am confused why this does not work here?
#include <stdio.h>
float a, b, c,min_value, max_value;
int main(){
printf("Enter a number here:");
scanf("%f",&a);
b=(max_value+min_value)/2;
while(abs(b*b-a)>0.1){
if (b*b>a){
max_value=b;
b=(max_value+min_value)/2;
}
else if(b*b<a){
min_value=a;
b=(max_value+min_value)/2;
}
printf("the square root of the number is %f",b);
}
}

In C, abs is an integer function - passing float values to it will result in truncation, so small values < +/-1.0 will just become 0. You need to use fabs for floating point values. Change:
while(abs(b*b-a)>0.1){
to:
while(fabs(b*b-a)>0.1){
and add:
#include <math.h>
near the top of your source file.

A lot of things are wrong:
float a, b, c,min_value, max_value;
You shouldn't declare these variables outside the main function.
b=(max_value+min_value)/2;
max_value and min_value are not defined, what are you expecting here?
if (b*b>a){
max_value=b;
b=(max_value+min_value)/2;
}
else if(b*b<a){
min_value=a;
b=(max_value+min_value)/2;
}
Once again, max_value and min_value may not be defined. I could continue.
If you are trying to implement a sqrt function, perhaps you should take a look at someone else's code, as it seems obvious you lack knowledge in C.

For future references, please state what your program is trying to accomplish and what errors are occuring. Not trying to be mean or condescending; just giving you a heads up on Stack Overflow policy on question phrasing.
That said, on a brief glance I did notice that you also did not define "max_value" or "min_value" before using them in line 6 (where you set a value to "b"). In addition, declaring your variables outside the main function makes them global variables, which I would suggest avoiding if your variables are not going to be used in another program (via "#include ").

Related

Creating a Fibonacci sequence in C

Consider a Fibonacci sequence whose values do not exceed four million. Find the sum of the even-valued terms. Your answer must be 4613732.
#include <stdio.h>
int main()
{
int a =0,b=1,c=0,sum=0;
while (c<=10){
int c=a+b;
a=b;
b=c;
if(c%2==0){
sum=sum+c;
}
}
printf("%d",sum);
return 0;
}
The output comes out to be blank. I tried 10 for smaller calculation time and the answer should be 2+8=10. I don't know what to do.
int c=a+b;
This doesn't modify the variable c that was declared outside the loop; it creates a new variable, whose scope is only the body of the loop. You just want c=a+b; here.
You have another bug in that on the iteration of the loop which increases c beyond its limit value, that value may still be added to the sum, even though it should not. For instance, if you replace the loop test with while (c <= 7), you will still get 10 as the answer, instead of the correct 2. Think about how to restructure the loop body to fix this.
The main problem is here:
int c = a + b;
You have redefined the variable c that shadows the original variable on each iteration. Remove the int declaration from there.
Also, note that you want to iterate up to 4 million to obtain your desired results. So, change the iteration limit from 10 to 4000000.*
* It is recommended declaring a macro constant on the top of the program to avoid magical numbers
int a = b+c is the main problem in your code. That line of code re defines the entire variable declaration. So instead u want to put c = a+b
#include <stdio.h>
int main()
{
int a =0,b=1,c=0,sum=0;
while (c<=4000000){
c=a+b; // just remove the `int` and this should fix it
a=b;
b=c;
if(c%2==0){
sum=sum+c;
}
}
printf("%d",sum);
return 0;
}
outputs: 4613732
In this question
int c=a+b;
You are not using the value declared outside of the method Insted you are defining a new variable that only works on inside of your method. Try removing the int decleration inside the while loop and It should work

rounding to desired digits in MATLAB and C

I've read the questions regarding the implementation of rounding in C, inspired by MATLAB round function and I followed their advice but the result is not at all what it should be. Here's part of my code regarding this issue:
movmean_h[i]=(double)sum/(f-b);
mexPrintf("\t movmean_h[%d]=%e",i,movmean_h[i]);
movmean_h[i]=(double)round(movmean_h[i]*n)/n;
mexPrintf("\t movmean_h[%d]=%e",i,movmean_h[i]);
And part of the result is like this(this code is run in a loop):
movmean_h[10261]=2.283693e-13 movmean_h[10261]=1.668138e-06
movmean_h[10261]=2.283693e-13 movmean_h[10261]=1.668138e-06
movmean_h[10262]=2.288172e-13 movmean_h[10262]=1.483963e-06
movmean_h[10263]=2.292687e-13 movmean_h[10263]=-8.838173e-07
movmean_h[10264]=2.297219e-13 movmean_h[10264]=0.000000e+00
movmean_h[10265]=2.292835e-13 movmean_h[10265]=2.138378e-06
movmean_h[10266]=2.288319e-13 movmean_h[10266]=1.409754e-06
movmean_h[10267]=2.283839e-13 movmean_h[10267]=0.000000e+00
movmean_h[10268]=2.279412e-13 movmean_h[10268]=-2.147484e-06
movmean_h[10269]=2.275056e-13 movmean_h[10269]=-2.147484e-06
movmean_h[10270]=2.270787e-13 movmean_h[10270]=-2.147484e-06
movmean_h[10262]=2.288172e-13 movmean_h[10262]=1.483963e-06
movmean_h[10263]=2.292687e-13 movmean_h[10263]=-8.838173e-07
movmean_h[10264]=2.297219e-13 movmean_h[10264]=0.000000e+00
movmean_h[10265]=2.292835e-13 movmean_h[10265]=2.138378e-06
movmean_h[10266]=2.288319e-13 movmean_h[10266]=1.409754e-06
movmean_h[10267]=2.283839e-13 movmean_h[10267]=0.000000e+00
movmean_h[10268]=2.279412e-13 movmean_h[10268]=-2.147484e-06
movmean_h[10269]=2.275056e-13 movmean_h[10269]=-2.147484e-06
movmean_h[10270]=2.270787e-13 movmean_h[10270]=-2.147484e-06
The answers do not match at all, not in order and not in the decimals, which in theory they would match.
And 'n' is defined as:
long int n=pow(10,15);
So my question is why my code is wrong, or is there something I'm missing?
By the way I am writing my C code for a MATLAB mex-file.
Code lacked a declaration of declaration of double round(). Older compilers allow this, yet interpret the result then an int. Code output is then quite bizarre. The hint, for me, was that many nearby double inputs had the same result.
// add
#include <math.h>
10^15 doesn't fit into a long int on a Windows machine. Use a double.
double n = pow(10, 15);
movmean_h[i]=(double)sum/(f-b);
mexPrintf("\t movmean_h[%d]=%e",i,movmean_h[i]);
movmean_h[i]=round(movmean_h[i]*n)/n;
mexPrintf("\t movmean_h[%d]=%e",i,movmean_h[i]);

What is the difference between the two locations?

I have a recursive program. When the printf is used in the function, it outputs 123 and when used outside, it outputs 0123 .
#include <stdio.h>
fact(int);
int main()
{
int x=3;
fact(x);
printf("\n");
system("PAUSE");
}
int fact(int y)
{
if (y > 0)
{
fact(y-1);
printf("%d",y);
}
//printf("%d",y);
}
I am not using both the printf at the same time . What difference does the location of this printf statement create?
Since your if condition looks for the values greater than zero, it is working as expected.
When the printf outside that IF block is used, it gets executed even when y is 0, which is not the case for the printf inside the IF block.
fact(int) is called by following sequence,
fact(3)-->fact(2)--->fact(1)--->fact(0)
The last call is fact(0). According to the implementation of fact(int), when 0 is passed in, 0 is printed if printf() is used outsite. 0 is not printed if printf() is used inside.
In fact, all the values passed into fact(int) is printed when printf() is used outsite.
I'd say one reason you didn't see the answer yourself is because your code is sloppy. Here are some complaints:
Your functions have no explicit return statements which are
especially important for understanding recursive code.
system() requires stdlib, but stdlib.h isn't included.
system("PAUSE") is unportable and unnecessary. Actually your code
would not run on my system because of this. See:
http://www.gidnetwork.com/b-61.html
Your question looks like homework, so this one is the homework's fault and not yours: because n! grows so quickly, factorial functions using 'int' for the return type can only calculate n! for 1<=n<=12, which is useless.
Try this exercise: write a one-line factorial function using a single return and a conditional assignment.

Is there a syntactic error that I'm overlooking in this loop

Hey guys could you please spot the semantic error that's in the code below, it seems OK to me but my instructor claims that there still is an "syntactic" error.
This is a simple program that prints a simple series starting from 256.
The series depends on the value of the variable a which is 256 in this case.
Hence in this case the series looks like 256,16,4,2,1. */
#include <stdio.h>
#include <math.h>
int main()
{
int a = 256;
int square_root_a;
printf("%d\n", a);
repeat:
square_root_a = sqrt(a);
if (square_root_a >= 2)
{
printf("%d\n", square_root_a);
a = square_root_a;
goto repeat;
}else{
printf("%d\n", 1);
} return 0;
}
You declare a as an integer, which will round the result of sqrt() to the nearest integer.
I guess you're supposed to use double.
Well, if it's not about the goto, or the int-ness of the variables, then my guess is your teacher means something subtle, like the printfs in both branches of the if. They have exactly the same purpose! Why write two statements that do the same, if it's possible to use only one? Just move the first one to above the if, and delete the second one.

C - definite integral Quadrature rule

I would apprecite a little help. I need to create simple application counting definite integral in quadrature rule, which is given as a parameter when running. I started with adding parametres, but when I use brackets in it, compiler won't compile my application. And then I am stuck in getting started, how to trasnfer parameter as a integral to some computing part?
Thanks
edit:
int x;
int i;
float sum=0;
double PI;
printf("Please enter the parts to divide the interval: ");
scanf("%d", &x);
for (i=1; i<x; i+=2){
if (i%4==1)
sum=sum+1./(double)i;
else
sum=sum-1./(double)i;
}
PI= 4*sum;
printf("The sum is %f\n", sum);
printf("Approximate value of PI is %f\n", PI);
It's hard to know what you're asking here.
Are you trying to do Gaussian or some other type of quadrature scheme with differing orders?
Are you having problems figuring out how to pass a function pointer to be evaluated by the numerical integration function?
When you say you have a compiler error, it suggests that you haven't even gotten to the point where you can tell whether your implementation works or not. How well do you know C? You should read and digest the error message and go back to a language reference to see where you went wrong until all the compiler errors are gone.
Once you achieve that, the fun begins: now you have to worrk about whether or not your code actually works.
UPDATE: I don't see any quadrature in the code you posted. Looks like a simple Euler or Simpson's rule.
I'd recommend something like "Numerical Recipes":
http://eiffel.ps.uci.edu/cyu/p231C/LectureNotes/lecture10:integration/lecture10.pdf

Resources