![]() |
Simple program odd results
Ive been out of coding practice for several months now so my debugging is rusty. I cant seem to figure out why Im getting the results that I am. Its a simple program used to aid my calculations in a diff. eq. course.
:
#include<stdio.h>:
Enter starting time:The for loop seems to be the root of the problem, and I wasnt getting expected behavior from the "n" variable so I tried to brute force a behavior (n = n + 1) but I still get back the previous value for n, and n seems to always increase by h no matter what I specify in the loop. I know this is a very trivial problem, but I cant figure out what the bug is. Thanks for the help. |
Re: Simple program odd results
My window for editing has expired and I thought I should add that Im getting correct approximations independant of the step size used. "n" just seems to not be playing nicely.
|
Re: Simple program odd results
:
for(n = 0; n <= 1/h; n++)Why are you incrementing n twice in the same for loop? The n++ in the loop declaration performs the n = n+1 for you.Edit: And as a side note. The <= comparator for an integer and float might not behave exactly as you expect. Look at the following sample. It says that 20 is not <= 20.0. But change n to 19, and you get True. :
|
Re: Simple program odd results
yes, using a float in the condition of a for loop isnt a good idea, but Im not sure if thats really the problem since it does execute the correct number of loops. I did discover that the printf statement of n has something to do with the odd results. Since its declared as an int and I try to print a float bad things happened and I would appreciate some insight into why.
:
#include<stdio.h>Outputs: :
n = -0.025121 |
Re: Simple program odd results
Your results are hardly surprising. You are attempting to print n out, but the %f format specifier tells printf() that n is a (double) floating point value. printf() will not magically convert n to a floating point value; it will print out the floating point value that happens to be represented with a double containing the same set of bits as the int named n.
Formally, passing an argument to printf() that doesn't match the corresponding format (eg using %f for an int) yields undefined behaviour. |
| All times are GMT -5. The time now is 3:57 AM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC