Converting double (or float) to int


After a little experimentation I see that with the g++ compiler on x86, when a double is converted to an int, the fractional part is discarded. Examples: int(0.7) == 0 int(1.3) == 1 int(-1.3) == -1 Is this behaviour consistent ...
Posted On: Monday 26th of November 2012 12:49:24 AM Total Views:  289
View Complete with Replies

RELATED TOPICS OF C Language PROGRAMMING LANGUAGE




Question on converting unsigned long to std::string

I need to convert unsigned long data to a std::string, I googled a bit to see if the string class supports any methods to achieve this - but didnt find any, I think of using sprintf and converting to a char buf and then putting it back in std::string - is anyone aware of any other way
VIEWS ON THIS POST

199

Posted on:

Saturday 3rd November 2012
View Replies!

Re: compiler converting char* to char*&

> Content-Type: text/plain; charset=ISO-8859-1 X-Original-Date: Wed, 10 Sep 2008 09:33:15 -0700 (PDT) X-Submission-Address: c++-submit@netlab.cs.rpi.edu On Sep 9, 6:00 pm, mojumbo wrote: > I am using gcc 3.2.2. > I have declared 'const char* bob = "Some String"; ' in a .h file > (Inherited code). > When I try to pass bob into a method requiring std::string, the > compilation pops because the compiler has made bob a 'const char*&' - > which std::string has no c-tor for. > > Any ideas There's nothing wrong with passing a reference to T to a function expecting a T. Your code "should" compile, and while I don't have gcc 3.2.x available, I have 3.3 and it compiles for me. Perhaps you could show a minimal code snippit that reproduces the problem. I'm suspecting either your code is not quite what you described, or you're (possibly) running into a compiler/library bug. You do have a fairly old compiler---have you tried with a newer one -- Chris -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ]
VIEWS ON THIS POST

252

Posted on:

Saturday 3rd November 2012
View Replies!

converting an ostream's output to a pure char*

Folks, I have a heterogenous env. where I developed some C++ code. This code has the '
VIEWS ON THIS POST

240

Posted on:

Saturday 3rd November 2012
View Replies!

Problem converting application from VS2003 to VS2005

Hi! I recently converted an application from VS2003 to VS2005. The application consists of a main 'unmanaged C++ executable' which calls a managed C++ .dll. The .dll basically launches a separate form. The application use to work fine in VS2003. Now that I have converted to VS2005 the main executable is working but an exception gets thrown when it trys to call the .dll (basically the new separate form never launches). The .dll was compiled with (/clrldSyntax). This is the exception that gets thrown: File: dbgheap.c Line: 1414 Expression: _CrtIsValidHeapPointer(pUserData) I click on Retry and it triggers a breakpoint at if ( (oldsize = _msize_crt(*pbegin))
VIEWS ON THIS POST

333

Posted on:

Saturday 3rd November 2012
View Replies!

converting floating point types round off error ....

Consider the equation (flight dynamics stuff): Yaw (Degrees) = Azimuth Angle(Radians) * 180 (Degrees) / 3.1415926535897932384626433832795 (Radians) There's a valid reason to use single precision floating point types. The number of decimal digits guaranteed to be correct on my implementation is 6. (i.e numeric_limits < float >::digits10 = 6 ) If I'm reading the IEEE standard, I'd could paraphrase the issue surrounding conversion to a string and back _without_ loss of precision as follows: If a float is correct to a decimal string with a least 6 significant decimal digits, and then converted back to a float, then the final number must match the original. IOW: given float a = 1. F ; float aa = 0. ; std::stringstream s ; s. precision ( 6 ) ; s aa; assert ( a != aa ) ; No sweat I have to serialize the Yaw answer above. The question: Is it safe to state that my PI representation is useless beyond six significant digits I'd like for the C++ source to reflect my Matlab models but I'm starting to get concerned here with the conversion aspect. Is there a good source out there that will show me how far out I could represent a value ( say PI ) for both single and double precision before truncation/round off loss kicks in ( I tend to struggle with numeric_limits at times + coupled with all the idiosyncrasies of machines and floating point types ) , On 2008-10-05 05:45:56 -0400, Paavo Helde said: > > Moreover, floating-point numbers are by nature inexact, No, floating-point numbers are exact. The problem is that they don't represent real numbers, and if you assume that they do, you don't get the results you expect. > so there seems to > be not much point for requiring the *exact* equality after serialization > and deserialization. It's not simple, but it can be done. -- Pete Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The Standard C++ Library Extensions: a Tutorial and Reference (www.petebecker.com/tr1book)
VIEWS ON THIS POST

344

Posted on:

Sunday 4th November 2012
View Replies!

Rounding error when converting from double to int

Steve McConnel, in his book "Code Complete", suggests converting money amounts from double to integer in order to avoid rounding errors during calculations. So we made a money class where the money amount is stored as an integer instead of a double. The cents are stored in the 10's and 1's position of the integer. For example: $1.23 is stored as the integer 123. The cents portion is 23, and the rest is the dollar portion. However we are having trouble initializing this integer amount when the original double amount contains fractions of a cent (due to some interest calculations). We want to round any fractional cents up to the nearest cent. We use a rounding scheme where values greater than or equal to 5 are rounded up. Below is our initialization function. Note that we use the type __int64 so we can hold larger numbers but the same problems happen with type int also. myCurrencyx100 is of the type __int64. The code multiplies the double by 100 first, then it rounds to the nearest 1, then it converts to int. So if value = 9.495 we want myCurrencyx100 to be initialized to 950. But the code sets it to 949. void GCSMoney::init( const double& value ) { if( value < 0 ) myCurrencyx100 = static_cast(100.0 * value - 0.5); else myCurrencyx100 = static_cast(100.0 * value + 0.5); } I experimented with the order of the calculations. I changed it to round to the nearest hundredth (cent), then multiply by 100, then convert to int. This will correctly set myCurrencyx100 to 950 when the double value is 9.495. But when I tried a double value of 1.115, it rounded it to 1.11 when it should have rounded it to 1.12. However the first init method worked for 1.115. void GCSMoney::init( const double& value ) { if( value < 0 ) myCurrencyx100 = static_cast(100.0 * (value - 0.005)); else myCurrencyx100 = static_cast(100.0 * (value + 0.005)); } So I have two different methods, but neither works with all values. For each of these methods, I noticed if I recoded the steps as individual lines of code, the error happens during the step when converting the double to int. Is there any commonly accepted practice for handling these types of errors
VIEWS ON THIS POST

264

Posted on:

Sunday 4th November 2012
View Replies!

converting some simple pseudocode to c++

all, I;m a beginner C++ and I;m trying to convert some pseudocode into C++. Its pseudo code of the peterson algorithm for N-processes. I almost converted the whole code. But the last lines are very hard. This is the pseudo code: for [ k=1 to n except k==i ] This is pretty simple code although I don;t know how to convert in into c++ because of the except in the pseudocode. for [k=1 to n] to c++ is for (k=1;k
VIEWS ON THIS POST

259

Posted on:

Sunday 4th November 2012
View Replies!

converting char to int (reading from a binary file)

I'm trying to read some binary data from a file, I've read a few bytes of the data into a char array with ifstream. Now I know that the first 4 bytes in the char array represent an integer. How do I go about converting the elements to an integer regards, Igor
VIEWS ON THIS POST

259

Posted on:

Sunday 4th November 2012
View Replies!

converting 'float (*)[4]' to 'const float**'

I know I am doing something stupid here, but it's friday night and I cannot see what is the issue here:
VIEWS ON THIS POST

202

Posted on:

Sunday 4th November 2012
View Replies!

ldap_get_values: converting UTF8 encoding to ANSI MBCS string on UNIX systems

I am using ldap_get_values() call to get the user attributes from LDAP. This call is returning the user attributes in UTF-8 encoding and its a PCHAR*. For normal English characters this is working well. When Multibyte characters are involved like Japanese, Chinese or Korean, I need to convert UTF8 to ANSI encoding to get the correct values. On Windows platform I am using MultiByteToWideChar() with the code page CP_UTF8 to convert it to wide character string and converting it back to ANSI string using the ATL macro W2A() with USES_CONVERSION. I need to do the same conversion on UNIX machines. I can think of mbstowcs() and wcstombs(). However these two calls don't change the encoding. Can someone let me know how do I change the encoding from UTF-8 to ANSI string on UNIX platforms (or same call which works on both UNIX & Windows)
VIEWS ON THIS POST

470

Posted on:

Monday 5th November 2012
View Replies!

Need help converting a string to a float...

I'm having this weird problem where my code does the following conversion from string to float: 27000000.0 -> 27000000.00 2973999.99 -> 29740000.00 2989999.13 -> 2989999.25 The number on the left is the string I get after tokenizing a bigger string. The number on the right is the number I get after the conversion. I've tried two different ways of converting, one way the older C way using atof, and another more C++ way. Either way, I get the same result. Can anyone shed some light on this for me Here's the code: string token; string tokens[14]; stringstream iss; getline(fin,bfr); while (getline(fin, bfr)) { iss > price; //price = atof(tokens[0].c_str());
VIEWS ON THIS POST

209

Posted on:

Monday 5th November 2012
View Replies!

converting char to float (reading binary data from file)

I'm trying to convert some char data I read from a binary file (using ifstream) to a float type. I've managed to convert the int types but now I need to do the float types as well but it doesn't seem to work. The code below is what I'm trying to use. Anyone see any obvious errors or have any hints/pointers regards, Igor float floatRead = 0; UINT32* ptr = (UINT32 *) (&floatRead); int offset = 0; for (int ii=startInd; ii
VIEWS ON THIS POST

242

Posted on:

Wednesday 7th November 2012
View Replies!

converting from unsigned char array to IPV6 string

Hi , I am trying to form an IPV6 address string from the address bytes contained in a unsigned char buffer char tempstring[35]; sprintf(tempstring, "%x:%x:%x:%x:%x:%x:%x:%x",htons(*((unsigned short *)(buf.GetStart()))),htons(*((unsigned short *)(buf.GetStart() +2))),htons(*((unsigned short *)(buf.GetStart()+4))),htons(*((unsigned short *)(buf.GetStart()+6))),htons(*((unsigned short *)(buf.GetStart() +8))),htons(*((unsigned short *)(buf.GetStart() +10))),htons(*((unsigned short *)(buf.GetStart() +12))),htons(*((unsigned short *)(buf.GetStart()+14)))) There is a stack over flow when I do this.Its becase tempstring is char instead of unsigned char. But sprintf allows only char array. How can I solve the problem.Is there a better way to write this Cheers, Sam
VIEWS ON THIS POST

231

Posted on:

Wednesday 7th November 2012
View Replies!

Accelerated C++ exercise 4-2 -- converting int to string?

Here's the question and the code I wrote for it. The // comment represents what I would like to do. Is there a really crude way of doing that -- because the book hasn't provided any fancy methods of doing it such as string streams, type casting, or anything like that -- or would you suggest a different approach /* 4-3. What happens if we rewrite the previous program to allow values up to but not including 1000 but neglect to change the arguments to setw Rewrite the program to be more robust in the face of changes that allow i to grow without adjusting the setw arguments. */ #include #include #include using std::cout; using std::endl; using std::setw; using std::string; int main() { int from = 1; int up_to = 1000; // int pad = length of up_to // int pad_square = length of (up_to * up_to) cout
VIEWS ON THIS POST

214

Posted on:

Wednesday 7th November 2012
View Replies!

converting a char* to a const char*

Hi: What is best and safest way of converting a char* to a const char * Can I use const_cast Cheers Sean.
VIEWS ON THIS POST

216

Posted on:

Wednesday 7th November 2012
View Replies!

Problem converting template function argument to boost::function

I've been experimenting with Boost.Function. I wrote a little test program, of which this is the guts: template void call_with_arg(function func, T arg) { func(arg); } void print_it(int x) { cout
VIEWS ON THIS POST

168

Posted on:

Wednesday 7th November 2012
View Replies!

converting to cb2007 from b5: iterators are const?

It seems iterator are const in 2007 and not only const_iterator This worked in builder 5 #include #pragma hdrstop #include using namespace std; struct MyClass { int id; int data; MyClass() : id(0), data(0) {} MyClass(int _id) : ...
VIEWS ON THIS POST

198

Posted on:

Saturday 10th November 2012
View Replies!

converting to utf8?

hi, i've not done much i18n stuff before but i was wondering how, if given a string (encoded as russian or kanji mb) how i would get this converted to utf8. i'm working with forte compiler on solaris i've something ...
VIEWS ON THIS POST

221

Posted on:

Saturday 10th November 2012
View Replies!

converting from IPADDRESS string to unsigned char array

On Sun, 30 Mar 2008 05:32:28 -0700, sam.barker0 wrote: > Hi , > I am trying to convert from an IPADDRESS string [say "12.12.1.2"]to a > unsigned char array[containing the octets witout the dots] > > I tried to use ...
VIEWS ON THIS POST

178

Posted on:

Sunday 25th November 2012
View Replies!

converting integer to a string(without the help of stringstreamvariable)

I am using a string variable in which I do lot of appending. The only difficulty I am facing as of now is appending a integer/float value to this variable. Although I can accomplish this task using a stringstream ...
VIEWS ON THIS POST

186

Posted on:

Sunday 25th November 2012
View Replies!