blah blah blah is here! blah blah » Close

up0down
link

I wrote a code for which

if 23E+20 is the input then output should be 230000000(20 zeros)

if 4.456E-14 is the input then 4.456000(14 zeros) should be the output

But its not working properly. Please let me know where I did error. Thank You.
using System;

class test

{

public static void Main()

{

Console.WriteLine("Enter double");

String ext =Console.ReadLine();



if(ext.IndexOf("E")!=-1)
{
int i=ext.IndexOf("E");

ext = ext.Substring(0, i);

for (int j = 0; j < int.Parse(ext.Substring(i + 1, ext.Length - (i + 1))); j++)

ext = ext + "0";

Console.WriteLine(ext);



}

}

last answered one year ago

2 answers

up0down
link

i don't know if 4.456E-14 is right coz it should be in the left but here is the code.

Console.WriteLine("Enter double");

String ext =Console.ReadLine();
int i=ext.IndexOf("E");
if (i != -1)
{
i++;
int exp = Math.Abs(int.Parse(ext.Substring(i, ext.Length - i)));
ext = ext.Substring(0, i-1);
for (int j = 0; j < exp; j++)
ext += "0";
}

Console.WriteLine(ext);
Console.Read();

up0down
link

This problem is more difficult than it looks.

Whilst muster's solution deals OK with integer mantissas with non-negative exponents, it doesn't deal with negative exponents and also doesn't deal with non-integral mantissas such as 4.456E-14.

The following does deal with them as long as you don't need more than 99 digits after the decimal point, if there is one. Rather than generating the additional zeros 'manually', it makes use of .NET's standard numeric format "F":

using System;

class Test
{
public static void Main()
{

Console.WriteLine("Enter q to quit at any time\n");

while(true)
{
Console.Write("Enter double : ");
string ext = Console.ReadLine().ToUpper(); // deals with 'e' as well
if (ext == "Q") return;

// make sure it's a valid double first
double d;

if(!double.TryParse(ext, out d))
{
Console.WriteLine("Not a valid double\n");
continue;
}

// get index of E if there is one
int i = ext.IndexOf("E");

if (i != -1)
{
char op = ext[i + 1]; // '+' or '-' or first digit
int pow;

if (op != '+' && op != '-')
{
pow = int.Parse(ext.Substring(i + 1));
}
else
{
pow = int.Parse(ext.Substring(i + 2));
if (op == '-') pow = -pow;
}

int dp = ext.IndexOf("."); // get index of decimal point, if any

if (dp == -1) dp = i; // if no dp, put an imaginary one where E is

int np = i - dp - pow; // decimal places, if any, to show for number
if (np < 0) np = 0; // can't be less than zero
if (np < 100) // can't deal with precision above F99
{
ext = d.ToString("F" + np.ToString());
if (np > 0) ext = ext.TrimEnd('0').TrimEnd('.'); // tidy up string
}
}
Console.WriteLine("Result is : {0}\n", ext);
}
}
}

Feedback