Nairaland Forum

Welcome, Guest: Join Nairaland / Login / Trending / Recent / New
Stats: 1263189 members, 1712806 topics. Date: Saturday, 01 November 2014 at 02:14 PM

C++ Question - Programming - Nairaland

Nairaland Forum / Science/Technology / Programming / C++ Question (1048 Views)

C# Question........help??? (1) (2) (3) (4)

(0) (1) (Reply) (Go Down)

C++ Question by nublet: 5:24am On May 27, 2012
Write a statement to print the left-most digit of a 5 digit number.

my solution is it correct?

[ N ] minus { 10 times [ the greatest integer in (N/10) ] }
Re: C++ Question by ektbear: 5:44am On May 27, 2012
Eh. That isn't C++ syntax. nor does it quite seem correct to me.

Basically, if N is the 5-digit #.

Well here is an example of what'd you do in another language:


octave:1> N=54321
N = 54321
octave:2> N/10**4
ans = 5.4321
octave:3> floor(N/10**4)
ans = 5


You shouldn't have much difficulty translating the above into C++.
Re: C++ Question by Beaf: 6:59am On May 27, 2012
Convert it to a char array. The value at [0] is what you want.
Re: C++ Question by ektbear: 7:00am On May 27, 2012
Char array? Eh.

Just divide by 10^4 and round down. A lot simpler.
Re: C++ Question by Beaf: 7:07am On May 27, 2012
.
Re: C++ Question by ektbear: 7:17am On May 27, 2012
Nah, it is pretty trivial.


#include <cmath>
#include <iostream>
using namespace std;

int main(){
long n = 99999; // Some 5 digit number
long woo = n/pow(10,4);
cout << "Result is " << floor(woo) << endl;
return 0;
}
Re: C++ Question by ektbear: 8:27am On May 27, 2012
Actually, the rounding down seems to be unnecessary. C++ float divided by integer cast into integer seems to automatically truncate for you:

#include <cmath>
#include <iostream>
using namespace std;

int main(){
float n = 99999; // Some 5 digit number
long woo = n/pow(10,4);
cout << "Result is " << woo << endl;
return 0;
}
Re: C++ Question by lordZOUGA(m): 10:39am On May 27, 2012
ekt_bear: Actually, the rounding down seems to be unnecessary. C++ float divided by integer cast into integer seems to automatically truncate for you:

#include <cmath>
#include <iostream>
using namespace std;

int main(){
float n = 99999; // Some 5 digit number
long woo = n/pow(10,4);
cout << "Result is " << woo << endl;
return 0;
}
your code wasted memory and is not reusable.
your main() should be (using ur algorithm)
int main(){
long n = 99999; // Some 5 digit number
int woo = n/pow(10,4);//since we need only the first digit

cout << "Result is " << woo << endl;
return 0;
}
I'll go with beaf's suggestion of using a char* array. It is more reusable than yours.
Re: C++ Question by lordZOUGA(m): 11:00am On May 27, 2012
#include <iostream>

using namespace std;

int main(){

long aNumber = 25632; //some number with irrelevant numer of digits

char* aString = static_cast<char*>(aNumber);

cout << "the first digit is: " << aString[0] << endl;
//or cast ur number back to int and use it for some stuff
//int myNumber = static_cast<int>(aString[0]);

return 0;
}
Re: C++ Question by mkwayisi: 11:28am On May 27, 2012
Am I missing something? What's up with this casting and long data types. Ain't it as simple as this:

#include <iostream>
int main()
{
int num = 12345;
std::cout << "Left-most digit: " << num / 10000;
return 0;
}
Re: C++ Question by lordZOUGA(m): 11:33am On May 27, 2012
mkwayisi: Am I missing something? What's up with this casting and long data types. Ain't it as simple as this:

#include <iostream>
int main()
{
int num = 12345;
std::cout << "Left-most digit: " << num / 10000;
return 0;
}
code reusability
Re: C++ Question by ektbear: 1:04pm On May 27, 2012
mkwayisi: Am I missing something? What's up with this casting and long data types. Ain't it as simple as this:

#include <iostream>
int main()
{
int num = 12345;
std::cout << "Left-most digit: " << num / 10000;
return 0;
}

So I wasn't aware that C++ actually automatically casts when you do integer divided by integer into an integer.

For example, in your example, technically the result is 1.2345. It seems that the default is to just truncate this to the integer 1, not the float 1.2345.

As I'm not a C++ programmer, I didn't know a priori what the behavior would be. Hence my initial call to floor().

Your version definitely works too.
Re: C++ Question by ektbear: 1:09pm On May 27, 2012
lordZOUGA: #include <iostream>

using namespace std;

int main(){

long aNumber = 25632; //some number with irrelevant numer of digits

char* aString = static_cast<char*>(aNumber);

cout << "the first digit is: " << aString[0] << endl;
//or cast ur number back to int and use it for some stuff
//int myNumber = static_cast<int>(aString[0]);

return 0;
}


This doesn't compile under g++:

woo2.cpp: In function ‘int main()’:
woo2.cpp:27:45: error: invalid static_cast from type ‘long int’ to type ‘char*’

Moreover, it seems some like a very clunky way of doing it. You are popping off digits from a number. Unnecessary to convert to a string first...
Re: C++ Question by ektbear: 1:12pm On May 27, 2012
Code reusability also doesn't seems so relevant, given that the task at hand is narrowly defined.

Plus, the proper generalization would be a function that returns the jth digit of a number.

Again, you can do this w/o converting to a string (similar sort of idea).
Re: C++ Question by ektbear: 1:19pm On May 27, 2012
Haha. So Ruby evidently does the same perverse thing that C++ does:

12500/1001.9.2-p318 :001 > 12500/10000
=> 1

Octave doesn't:
octave:1> 12500/10000
ans = 1.2500

Python behaves properly:
>>> 12500/10000
1.25

Java does the same thing as C++:
bsh % System.out.println(12500/10000);
1


Perverse default behavior, C++, Java, and evidently my beloved Ruby cry
Re: C++ Question by ektbear: 1:20pm On May 27, 2012
lordZOUGA:
your code wasted memory.

Finally, compilers are smart. It will optimize this away for me...no need to worry about it when writing code.
Re: C++ Question by lordZOUGA(m): 1:51pm On May 27, 2012
ekt_bear:


This doesn't compile under g++:

woo2.cpp: In function ‘int main()’:
woo2.cpp:27:45: error: invalid static_cast from type ‘long int’ to type ‘char*’

Moreover, it seems some like a very clunky way of doing it. You are popping off digits from a number. Unnecessary to convert to a string first...
oh well, wrote that on my phone... Guess I was wrong in converting it to a pointer..

Seems clunky but for an unknown number of digits...
Re: C++ Question by lordZOUGA(m): 1:58pm On May 27, 2012
ekt_bear:

Finally, compilers are smart. It will optimize this away for me...no need to worry about it when writing code.
no, it won't optimize but it will compile. It will set aside space like you specified
Re: C++ Question by Beaf: 10:01pm On May 27, 2012
lordZOUGA: #include <iostream>

using namespace std;

int main(){

long aNumber = 25632; //some number with irrelevant numer of digits

char* aString = static_cast<char*>(aNumber);

cout << "the first digit is: " << aString[0] << endl;
//or cast ur number back to int and use it for some stuff
//int myNumber = static_cast<int>(aString[0]);

return 0;
}

I agree with this approach, its basically what I suggested earlier and the most natural and non-destructive way (that there are minor syntax errors is beside the point).
A char is a small version of an int in laymans terms, you can do math on it etc.
Re: C++ Question by ektbear: 10:11pm On May 27, 2012
lordZOUGA:
no, it won't optimize but it will compile. It will set aside space like you specified

So compilers are smart enough to recognize that, "hey, this variable actually can fit in smaller amounts of space. Let me use an int instead of the long he specified."

So yes, it will optimize. You can probably compile the two different versions and the inspect the file size or assembly code. Likely identical output..
Re: C++ Question by ektbear: 10:19pm On May 27, 2012
lordZOUGA:
oh well, wrote that on my phone... Guess I was wrong in converting it to a pointer..

Seems clunky but for an unknown number of digits...

I don't think your code works at all. From my investigations, you can't just convert an integer into a string. You'll need to call some library function to do the work for you (e.g., sprintf() or C++ iostreams).

Something like this: http://www.cplusplus.com/articles/D9j2Nwbp/

But as I stated earlier, this is a very strange way to solve the problem. If someone asks me for the left-most digit of a 2 digit number, I'd just divide. Not convert to a string first. Same for an arbitrary K digit number.
Re: C++ Question by ektbear: 10:24pm On May 27, 2012
Indeed. Compilers are quite a bit smarter than you give them credit for.

The size of the C++ code in which I used a long is 9383 bytes on my system. Using int instead gives me 9383 bytes.

So actually didn't waste anything at all for me to use a long rather than an int.

It would have hurt for dynamic memory allocation of course. But clearly for static, the compiler optimizes away.

And the GNU compilers are probably some of the worst as far as optimization goes...no doubt Intel compilers would even more aggressively optimize.
Re: C++ Question by Nobody: 10:51pm On May 27, 2012
Re: C++ Question by ektbear: 11:16pm On May 27, 2012
My statement is correct.

The portability of the GNU compilers is nice.

But that doesn't mean that they produce code as efficient as Intel compilers.

I highly doubt that GNU-compiled code is as efficient as that of any commercial compiler. Hence, the statement is correct.
Re: C++ Question by Nobody: 11:41pm On May 27, 2012
Re: C++ Question by ektbear: 11:54pm On May 27, 2012
There is always going to be a special case in which Compiler X produces "better" code (in whichever way you define 'better') than Compiler Y.

But the more important questions are:
a) for my particular case, which compiler is best?
b) which compiler typically performs better across most applications?

Perhaps for the applications you deal with, there is no difference. That is fine. However, for many other applications of interest to people (http://stackoverflow.com/questions/1733627/anyone-here-has-benchmarked-intel-c-compiler-and-gcc), there is a difference, and Intel wins hands down.

(b) is a more difficult question to answer and benchmark. However, my recommendation would be that anyone who has access to the latest Intel compiler for their system should use it over GCC.

Commercial generically does not mean superior, yes. But one might expect that the compiler designed by the same guy who designed the chip might perform better than a compiler written by some third party. So if you can afford it, go with the Intel compiler.
Re: C++ Question by Beaf: 12:23am On May 28, 2012
Regardless of how a division is optimised, it is a destructive way to do a straightforward thing which is create a stream of chars which are numbers too.
In realtime systems, some micro circuits etc, division would be out the door.
Re: C++ Question by ektbear: 12:32am On May 28, 2012
1. There is nothing "destructive" about division. Nothing is getting destroyed here..
2. Division isn't particularly computationally expensive, to my knowledge. Same computational complexity as multiplication. And your processor will have specialized circuits to do it fairly efficienctly.
3. I don't know of any way to convert an X digit integer into a stream of characters without doing some sort of division. How on earth does one convert the number 12345 into the string "12345" without popping off digits? And the only way I know of to pop off digits is to do division.
If you are calling some function that converts an integer into a string representation, under the hood it is probably doing a sequence of digit operations like that of the original function I had.
Re: C++ Question by ektbear: 12:35am On May 28, 2012
Which real-time systems don't allow you to perform division? undecided

So you can do integer to string conversion on a real-time system, but not division by 10? grin

lol
Re: C++ Question by ektbear: 12:38am On May 28, 2012
I don't even understand the way you guys reason.

You want to build a box which does this:

Integer->[f(x)] -> Left-most digit

Rather than doing it in the most direct way possible, you guys want to do:

Integer->Convert to string representation->grab left-most character of string->convert this left-most character back to digit.

Seems so unnecessary, roundabout, and wasteful.
Re: C++ Question by lordZOUGA(m): 12:49am On May 28, 2012
you were right, my initial code was wrong. you can only do static_casts between base classes and derived classes.
Converting to a stringstream will work but I was looking for a way to use only the iostream class to write reusable code for that problem.
Re: C++ Question by Beaf: 12:49am On May 28, 2012
ekt_bear: Which real-time systems don't allow you to perform division? undecided

A lot of the time you make really stup!d arguments. Do you know how many clock cycles a division takes vs addition or subtraction?
Have you ever coded image recognition or realtime video manipulation? What you don't know, dont argue about.
Division is avoided like the plague in such systems, you limit your operations as much as possible to additions and subtractions which are fast operations. If I ever need to divide, then I make it a power of two for bit shifting.

Thats the way it rolls. Law of nature.

ekt_bear:
So you can do integer to string conversion on a real-time system, but not division by 10? grin

lol

You would only need to convert once. After that, calling any array index any number of times is the fastest thing on Earth.

(0) (1) (Reply)

Share Your Mobile Phone Application Made By You / Coding Challenge 1: Permutations / How To Modify Simple Machine Forum (SMF)

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (0) (1) (2) (3) (4) (5) (6) (7) (8) (9)

Nairaland - Copyright © 2005 - 2014 Oluwaseun Osewa. All rights reserved. See Nairalist and How To Advertise. 123
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.