Sign in to follow this  
@root

logarithm for integers

Recommended Posts

I'm creating a little program that squares the numbers 1 to x. The problem I'm having is that I want the two columns(x and x^2) nicely lined up, which I have to do with the s.width(n) and setw(n) functions(it's an exercise from a book). This is how far I've gotten:
#include <iomanip>
#include <ios>
#include <iostream>
#include <math.h>

using namespace std;

int main()
{
	const int numbers = 100;
	const int biggestPlusOne = log10(numbers) + 2;

	streamsize strwidth = cout.width();
	for (int i = 1; i <= numbers; ++i)
	{
		int numSize = log10(i) + 1;
		int ansSize = log10(i * i) + 1;
		int width = biggestPlusOne + ansSize - numSize;
		cout << i << setw(width) << i * i << endl;
	}

	return 0;
}
I hope the program is selfexplanatory... The idea is that 10logx + 1 gives me the number of digits IF it is rounded down. So in order to get rouded figures, I used integers as arguments. What I found out is that the function log10() doesn't accept integers. Does anybody have an idea on how to get around this issue?

Share this post


Link to post
Share on other sites
Ok, the problem has been solved:
#include <iomanip>
#include <ios>
#include <iostream>
#include <math.h>

using namespace std;

int main()
{
const int numbers = 100;
const int biggestPlusOne = (int)log10((double)numbers) + 2;

streamsize strwidth = cout.width();
for (int i = 1; i <= numbers; ++i)
{
int numSize = (int)log10((double)i) + 1;
int ansSize = (int)log10((double)i * i) + 1;
int width = biggestPlusOne + ansSize - numSize;
cout << i << setw(width) << i * i << endl;
}
setw(strwidth);

return 0;
}



With typecasting I transformed the integers to doubles and the answers back to integers.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this