Sunday, July 12, 2009

Can any body tell me what's wrong with this c++ function and loop?

1. I am trying to create a function that doesn't allow the input of alphabets... only digits and decimal point. The input is stored in a string and then the value is assigned to a variable which is returned by the function.The problem is that when i press Enter(just like scanf) nothing happens although i have considered this. Take a look at the function:-








double getinput()


{


int n=1000,k,z,c=0;


char N[100];





double x;


for(k=0;k%26lt;=n-1;k++)


{


do


{





N[k]=_getch();





if (N[k]=='\n')


break;


if (N[k]=='.')


{z=k;c++;}


if(('0'%26lt;= N[k] %26amp;%26amp; N[k]%26lt;='9') || N[k]=='.')


printf("%c",N[k]);





}


while((!('0'%26lt;= N[k] %26amp;%26amp; N[k]%26lt;='9')) || (N[k]!='.' %26amp;%26amp; c!=1) || (N[k]!='\n'));


if (N[k]=='\n')


break;


}





for(k=0;k%26lt;=n-1;k++)


{


if(k==z || N[k]=='\n')


continue;


if(k%26lt;z)


x+=(float)N[k]*pow(10.0,z-k-1);


if(k%26gt;z)


x+=(float)N[k]*pow(10.0,z-k);


}


return x;


}


2.Is this infinite?


for(n=low;n%26lt;=up;n+=(1/10)*(up-low))

Can any body tell me what's wrong with this c++ function and loop?
You forgot to reverse the logical operators when you reversed the sense of the tests. Try changing the test in the do/while to:


while((!('0'%26lt;= N[k] %26amp;%26amp; N[k]%26lt;='9')) %26amp;%26amp; (N[k]!='.' %26amp;%26amp; c!=1) %26amp;%26amp; (N[k]!='\n'));


(|| became %26amp;%26amp; in 2 places)


I did not read any farther.





The 2nd question is chopped, but I'll take a guess:


If 'up' is changing as a side effect in the increment portion (or in the body), the loop can become infinite.


Also, if the increment portion is integer and gets truncated to 0 in the calculation, the loop becomes infinite.
Reply:I think you should compare Ascii values rather than comparing string letter explicitly.





It will make your work easier too





Hope this helps


Cheers:)


No comments:

Post a Comment