objective c - Conversion from float to int looks weird -


i having difficulty understanding why following code giving me numbers below. can explain conversion float int? (pclocation cgpoint)

counter = 0; pathcells[counter][0].x = pclocation.x; pathcells[counter][0].y = pclocation.y; cellcount[counter]++;     nslog(@"%@",[nsstring stringwithformat:@"pclocation at:  %f,%f",pclocation.x,pclocation.y]); nslog(@"%@",[nsstring stringwithformat:@"path cell 0: %i,%i", pathcells[counter][cellcount[counter-1]].x,pathcells[counter][cellcount[counter]].y]); 
2012-03-09 01:17:37.165 50levelsbeta1[1704:207] pclocation at: 47.000000,16.000000 2012-03-09 01:17:37.172 50levelsbeta1[1704:207] path cell 0: 0,1078427648 

assuming code otherwise correct:

i think understand how nslog , other printf-style functions work. when call nslog(@"%c %f", a_char, a_float), code pushes format string , values onto stack, jumps start of function's code. since nslog accepts variable number of arguments, doesn't know how pop off stack yet. knows @ least there format string, pops off , begins scan it. when finds format specifier %c, knows pop 1 byte off stack , print value. finds %f, knows pop 32 bits , print floating point value. reaches end of format string, it's done.

now here's kicker: if lie nslog , tell providing int provide float, has no way know lying. assumes telling truth , prints whatever bits finds in memory asked printed.

that's why seeing weird values: printing floating point value though int. if want int value, should either:

  1. apply cast: nslog(@"cell.x: %i", (int)cell.x);
  2. leave float use format string hide decimals: nslog(@"cell.x: %.0f", cell.x);

(alternate theory, still potentially useful.)

you might printing out contents of uninitialized memory.

in code you've given, counter = 0 , never changed. assign values to:

pathcells[0][0].x = pclocation.x; pathcells[0][0].y = pclocation.y; cellcount[0]++; 

then print:

pathcells[0][cellcount[-1]].x pathcells[0][cellcount[0]].y 

i'm pretty sure cellcount[-1] isn't want. c allows because though think of working array of specific size, foo[bar] means grab value @ memory address foo plus offset bar. index of -1 means take 1 step back. that's why don't warning or error, junk data.

you should clarify pathcells, cellcount, , counter , how relate each other. think have bug in how combining these things.


Comments

Popular posts from this blog

delphi - How to convert bitmaps to video? -

jasper reports - Fixed header in Excel using JasperReports -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -