The question:
8 children's height is being checked, and inserted.
Insert 8 double values into the console, and make an algorithm to find out the lowest height & the maximum height.
So this is what I've done:
class work1 {
public static void Main(String[] args) {
string[] height = Console.ReadLine().Split(' ');
double[] heightInDouble = new Double[height.Length];
for (int i = 0; i <= height.Length; i++) {
heightInDouble[i] = (double) height[i]; // line 20
}
Console.WriteLine("Highest: " + heightInDouble.Max() + " Lowest: " + heightInDouble.Min());
}
}
The results:
Error: Cannot convert type 'string' to 'double' (20)
How can I convert a string to a double value ?
You can't directly cast from string to double. Use double.Parse
:
realInts[i] = double.Parse( ints[i] );
You may also want to use TryParse
, as it's not certain here that the string is actually a number:
double parsedValue;
realInts[i] = double.TryParse(ints[i], out parsedValue) ? parsedValue : 0;
One more note: you could simplify the syntax by using a Linq expression chain:
double parsedVal;
double[] realInts = Console.ReadLine().Split(' ')
.Select(str => double.TryParse(str, out parsedVal) ? parsedVal : 0)
.ToArray();
Try this.
static void Main(string[] args)
{
string[] ints = Console.ReadLine().Split(' ');
double[] realInts = new Double[ints.Length];
for (int i = 0; i <= ints.Length; i++)
{
double val;
if (Double.TryParse(ints[i], out val))
{
realInts[i] = val; // line 20
}
else
{
// Unable to parse
realInts[i] = 0;
}
}
}
use this code
class work1
{
public static void Main(String[] args)
{
string[] height = Console.ReadLine().Split(' ');
double[] heightInDouble = new Double[height.Length];
for (int i = 0; i < height.Length; i++)
{
heightInDouble[i] = Convert.ToDouble(height[i]); // line 20
}
Console.WriteLine("Highest: " + heightInDouble.Max() + " Lowest: " + heightInDouble.Min());
Console.ReadLine();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.