I'm trying to convert my C# class library over to C++ and was wondering if this is how scientific notation should look. Any pointers would be nice.

// Scientific Notation?
private int i = 0;
private string Sign = "";

public string Output = "";

public void Sci(double x)
{
	if (x > 1)
	{
		for (int p = 0; x > 10.0f; p++)
		{
			i = p;
			x /= 10.0f;
		}

		Sign = "";
	}

	else if (x < 1)
	{
		for (int p = 0; x < 1; p++)
		{
			i = p;
			x *= 10.0f;
		}

		Sign = "-";
	}

	Output = x->ToString() + " * 10^(" + Sign + i->ToString() + ")";
}

Recommended Answers

All 3 Replies

To output a double in scientific notation:

double x = 123.4567;
cout << scientific << x << endl;

I'm trying to build it as a class library not a console app.

I'm trying to build it as a class library not a console app.

I see. You can use the same method with a std::stringstream object instead of stdout:

#include <iostream>
#include <sstream>
#include <string>

std::string Sci( double x )
{
    // Make a stringstream that will do the conversion for us
    std::stringstream ss;
    
    // Insert the double into the stringstream, using scientific formatting
    ss << std::scientific << x;
    
    // return the result as a std::string
    return ss.str();
}

int main()
{
    double x = 123.4567;

    // Make a string
    std::string s;
    
    // convert the double to a string, in scientific notation
    s = Sci(x);

    // Check that we have the desired effect
    std::cout << s << std::endl;

    return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.