find squareroot with a loop - c

double sqrtIt(double x, double low_guess, double high_guess) {
int n = 10;
int num = 0;
while ( n > 0.000000000000001){
n = n / 10;
while (num < x && low_guess <= (low_guess * 10)){
low_guess = low_guess + n;
num = low_guess * low_guess;
}
}
return low_guess;
}
I've tried to use the code above to find the square root of a number. the function works fine most of the time, but when the number is 2, I get the "There is no source code available for the current location. Show disassembly" error from line num = low_guess * low_guess; I don't know what did wrong, and what does show disassembly do? Thanks

The "no source code available" message may indicate that you are not compiling in debug mode, so your IDE can't do a source-level debug. I think there's probably some confusion here, brought on by trying to deal with an IDE for the first time...
As others have said, you should probably declare n and num to be double, not int.
Probably, once you become more familiar with your development environment (as well as the language), some of these things will sort themselves out.

There are some problems with this function, but this seems to be a very strange error to get from that code. I think you made some other error somewhere else in your program, and that error is then causing this problem.

is there a typo in your code?
low_guess <= (low_guess * 10 ) is always true for non negative number...

Even if it worked it would be pretty inefficient. I guess you wanted to write something like this
double sqrtIt(double x)
{
double guess1, guess2;
guess1=1.0;
do
{
guess2=x/guess1;
guess1=(guess1+guess2)/2;
}
while (abs(guess1,guess2)<0.0000001);
return guess1;
}

Related

My code returns an unexcpected value

Sorry for the generic question but I've come across a behaviour in my code that I can't explain and that I find relevant for further users.
There is the screenshot of my screen when it happend. It's a repeatable error that happend any time my code runs.
screenshot
and there is the text version of it.
My code runs a function
inline static int isInBounds(SDL_Surface* img,int x,int y){
if((x<0)||(x >= img->w)||(y<0)||(y >= img->h) ) return 0;
return 1;
}
I ran my code using gdb and I got the results
(gdb) print isInBounds(surface,x,y)
$1 = 1
(gdb) print y >= surface->h
$2 = 1
I don't get it. If (y >= surface->h) = 1, shouldn't the function isInBounds(surface,x,y) return 0 since the if statement is fulfilled ?
The error solved itself one day when I re-run it. Gods know what happened.

Board game functions

I have made a program to a board game. My problem is a function, so that certain fields transport the player back or forward. Apparently the thing I did doesn't work.
int numbers()
{
int maxscore;
int numbers[10];
maxscore = enter();
srand(time(NULL));
int nonumbers[3] = {0, 1, maxscore}; //to initialize the scores there shouldn't be a badfield
numbers[10] = rand() % maxscore + 1;
if(numbers[10] == nonumbers[3])
{
numbers[10] = rand() % maxscore + 1;
}
return numbers;
}
int badfields = numbers();
if(score[i] == badfields)
{
printf("Player %d. goes 5 fields backwards", playershown);
score[i] = score[i] - 5;
printf("This player is now in %d Field", score[i]);
}
Somehow I have to repeat the process of entering the maximum score.
I won't directly answer the "question" because there is no "question" to be answered. As others have pointed out in the comments, you need to be more specific and provide a proper description of your problem. But I can still provide the following feedback:
It seems to me you don't quite understand arrays and their indexing. For example, this line should give you a segmentation fault error, or at the very least make a comparison with an unknown value:
if(numbers[10] == nonumbers[3])
This is because your nonumbers array has 3 elements, and thus they should be addressed as nonumbers[0], nonumbers[1] or nonumbers[2] (or, in general, as Weather Vane put it in the comments, from nonumbers[0] to nonumbers[array_lenght-1]). nonumbers[3] will access an undefined position in memory. Your problem could be related to this.
Note that neither me nor anybody is going to review your entire code
to find the error. As stated above, please be more specific.
Also, are you sure you got rid of all compiler errors? Because further down your code you have an uninitialized variable i. To be sure you got rid of all potentially nasty errors, open the terminal (I'm assuming you are on linux) and use the following command to compile your program:
gcc *.c -Wall -Wextra -o program
Then run it with:
./program

Function crashing in release mode but runs flawless in debugger

My program crashes on this function on the 7th line, when I call malloc() when I run in release mode I get the `Program.exe has stopped working message, and when I run in debugger, most of the time it succeeds but sometimes I get this message (especially on larger input):
MONOM* polynomialsProduct(MONOM* poly1, int size1, MONOM* poly2, int size2, int* productSize)
{
int i1, i2;
int phSize = 1, logSize = 0;
MONOM* product;
product = (MONOM*)malloc(phSize*sizeof(MONOM));
monomAllocationVerification(product);
for (i1 = 0; i1 < size1; i1++)
{
for (i2 = 0; i2 < size2; i2++)
{
if (logSize == phSize)
{
phSize *= 2;
product = (MONOM*)realloc(product,phSize*sizeof(MONOM));
monomAllocationVerification(product);
}
product[logSize].coefficient = poly1[i1].coefficient * poly2[i2].coefficient;
product[logSize].power = poly1[i1].power + poly2[i2].power;
logSize++;
}
}
mergeSort(product,logSize);
*productSize = sumMonomsWithSamePower(product, logSize);
return product;
}
I understand that I'm dealing with memory errors and problems, but is there any quick way to analyze my code and look for memory errors? I look at my code a dozen of times looking for this kind of errors and found nothing. (I didn't want to post the code here since its 420 lines long).
First of all, if heap corruption is detected on the first malloc, that means it happened earlier (not in this function or on previous pass). So the problem may lie outside this code.
However, the code also looks suspicious to me.
monomAllocationVerification has no size parameter, so it should work on one monom only, yet you call it only once after realloc on pointer to first element, despite having allocated space for quite a few monoms. Please clarify your decision.
It is a bit unclear why sumMonomsWithSamePower should return a size, and thus modify an array to store a value. May be a quirk, but still suspicious.
UPDATE
The problem was in other functions; a few reallocs with wrong size.
I would check the return value of malloc() and use perror() to describe what error has occured. Also here is the documentation for malloc() and perror().
if((product = (MONOM*)malloc(phSize*sizeof(MONOM))) == NULL)
{
perror("ERROR: Failed to malloc ");
return 1;
//perror() will display a system specified string to describe the error it may tell you the error
}
Also do you know the size of MONOM? If not add the following line to your code.
printf("MONOM SIZE = %i\n", sizeof(MONOM));

While loop not behaving as expected

I am working in an assignment and am experiencing some weird stuff. I have this while loop in my program that does not seem to branch into the for loop. I have placed two print statements and only the "1" prints over and over again. Note that this only happens when I compile and run from the linux terminal. Now what seem weird is that if i run the exact same code (while loop plus everything else) in Netbeans it seems to compile and behave as expected. Anyone know what might be wrong. Here is the code. I appreciate your help.
while(strstr(p,string_a)!= NULL)
{
p = trailerp + pholderp;
long int index = strstr(p,string_a) - (p+1); // -1 where it hits
printf("1");
for( i = 0; i <= index; i++)
{
printf("2");
p2[trailerp2] = pholderp[trailerp];
trailerp++;
trailerp2++;
if(i == index)
{
int j;
for(j=0; j <= lenb-1; j++) // insert the new string
{
p2[trailerp2] = string_b[j];
trailerp2++;
}
trailerp++;
}
}
}
Edit: I have found the problem. Netbeans seems to be broken in this OS.
This is because strstr(p,string_a) returns either p or 0 in this part:
long int index = strstr(p,string_a) - (p+1); // -1 where it hits
which results in index < 0 and prevents going into the loop.
You must print both p and string_a immediately before this statement to see what is going wrong there.

C programming. Why does 'this' code work but not 'that' code?

Hello I am studying for a test for an intro to C programming class and yesterday I was trying to write this program to print out the even prime numbers between 2 and whatever number the user enters and I spent about 2 hours trying to write it properly and eventually I did it. I have 2 pictures I uploaded below. One of which displays the correct code and the correct output. The other shows one of my first attempts at the problem which didn't work correctly, I went back and made it as similar to the working code as I could without directly copying and pasting everything.
unfortunately new users aren't allowed to post pictures hopefully these links below will work.
This fails, it doesn't print all numbers in range with natural square root:
for (i = 2; i <= x; i++)
{
//non relevant line
a = sqrt(i);
aa = a * a;
if (aa == i);
printf("%d ",i);
}
source: http://i.imgur.com/WGG6n.jpg
While this succeeds, and prints even numbers with natural sqaure root
for (i = 2; i <= x; i++)
{
a = sqrt(i);
aa = a * a;
if (aa == i && ((i/2) *2) == i)
printf("%d ", i);
}
source: http://i.imgur.com/Kpvpq.jpg
Hopefully you can see and read the screen shots I have here. I know that the 'incorrect code' picture does not have the (i/2)*2 == i part but I figured that it would still print just the odd and even numbers, it also has the code to calculate "sqrd" but that shouldn't affect the output. Please correct me if I'm wrong on that last part though.
And Yes I am using Dev-C++ which I've read is kinda crappy of a program but I initally did this on code::blocks and it did the same thing...
Please I would very much appreciate any advice or suggestions as to what I did wrong 2 hours prior to actually getting the darn code to work for me.
Thank you,
Adam
your code in 'that' includes:
if (aa == i);
// ^
printf(...);
[note the ; at the end of the if condition]
Thus, if aa == i - an empty statement happens, and the print always occures, because it is out of the scope of the if statement.
To avoid this issue in the future, you might want to use explicit scoping1 [using {, } after control flow statements] - at least during your first steps of programming the language.
1: spartan programmers will probably hate this statement
Such errors are common. I use "step Over", "Step Into", "Break Points" and "watch window" to debug my program. Using these options, you can execute your program line by line and keep track of the variables used in each line. This way, u'll know which line is not getting executed in the desired way.

Resources