• Advertisement
Sign in to follow this  

logarithm for integers

This topic is 4159 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Sign in to follow this  

  • Advertisement