Giving an error saying local variable is not assigned - c#

This is a simple code I have written to solve a mathematical problem.
namespace StoreCredit
{
class Program
{
private static int No1;
static void Main(string[] args)
{
string[] text = System.IO.File.ReadAllLines(#"input.txt");
int nocases = int.Parse(text[0]);
int J = 1;
int No1=0;
int No2=0;
for (int x = 1; x <= nocases;x++ )
{
int Amount = int.Parse(text[J]);
int NoItem = int.Parse(text[J+1]);
char[] delimiterChars = { ' ' };
string[] Values = text[J+2].Split(delimiterChars);
int z = 0;
bool found = false;
while ((z < NoItem) && !found)
{
int Item = int.Parse(Values[z]);
int Remaining = Amount - Item;
int y = 0; bool found2 = false;
while ((y < NoItem) && !found2)
{
if (Remaining == int.Parse(Values[y])&&!(y==z))
{
Console.WriteLine("Found a match");
found = true;
found2 = true;
Console.WriteLine("Value 1 = {0} and Value 2={1}",(z+1),(y+1));
}
y++;
}
z++;
}
string lines = "Case #" + x + ": ", z, y;
StreamWriter file2 = new StreamWriter(#"output.txt", true);
file2.WriteLine(lines);
file2.Close();
J = J + 3;
}
}
}
}
I wanted to write the out put of this program to a text file. But I get an error saying z,y cannot be declared in this scope because it would give an different meanings to z,y. Can you please explain me the reason for this.
Thank you

This line near the end attempts to re-declare z and y, since you've separated them by commas:
string lines = "Case #" + x + ": ", z, y;
Did you intend to concatenate them instead? Such as:
string lines = "Case #" + x + ": " + z + y; // notice the + instead of comma

Related

How do I graph a-b=0?

Lets say a=x+y and b=2x-y and I want to plot a-b=0. I can manually rewrite this from (x+y)-(2x-y)=0 to y=.5x which makes it trivial to graph, but how do I rewrite it in code? Given x how do I calculate y if all I have is (x+y)-(2x-y)=0?
To be more specific, I am trying to graph the decision boundary of a neural network. I want to be able to change the layers and outputs at will, essentially changing the function I get as an output.
This is an example of an output I could get:
(x_1 w_2 + x_2 w_2 + b_1) w_7
+ (x_1 w_3 + x_2 w_4 + b_2) w_8
+ (x_1 w_5 + x_2 w_6 + b_3) w_9
+ b_4 (x_1 w_1 + x_2 w_2 + b_1) w_10
+ (x_1 w_3 + x_2 w_4 + b_2) w_11
+ (x_1 w_5 + x_2 w_6 + b_3) w_12
+ b_5
It's a 1 by 2 matrix and I know all values except x2 which is the y-axis. In order to draw the decision boundary I have to calculate a-b=0 where a and b both contain x and y. I can manually separate y to get y=... ,but that's not an option if the results in the output matrix change. How do I seperate/calculate the y?
I am using c# in Unity and passing the points on the graph into the LineRenderer.
Alright, I found the solution the same day of posting the question but had already been messing about for days. It turned out to be a math question after all.
Here's a link to the specific setup for the neural network using a linear activation: https://www.desmos.com/calculator/crmeebqnfb
I manually rewrote the matrix multiplication for this specific setup into a function and was looking for a way to do that for any size and number of invisible layers.
The solution I found is to separate the input matrix into x1 and x2 and separately do the matrix multiplication for them. The x1 value gets the biases added but the x2 doesn't and the first weight matrix has to be split in 2 so x1 can get multiplied with the first row and x2 with the second row.
If you then do the matrix multiplication from there you'll get two 2 matrices like this:
[firstx1answer secondx1answer] [firstx2answer secondx2answer]
And then you can put them into this function:
Edit for better clarification:
Maybe a bit confusing but here's my code. CreateDecisionBoundaryPoints is where this is implemented:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using System.IO;
using System;
[ExecuteAlways]
public class Controller : MonoBehaviour
{
public Transform LineRenderer;
public GameObject textPrefab;
public GameObject pointPrefab;
public Transform weightsUI;
public Transform biasesUI;
[Range(.001f, .1f)] public float delta;
public int numberOfHiddenLayers;
public bool debugWeightMatrices;
public bool debugBiasMatrices;
[HideInInspector] public string[] dataValues;
private void Start()
{
if (Application.isPlaying)
{
//read file
int numberOfLines;
dataValues = ReadData("D:\\Documents\\Unity Projects\\Learning Machine Learning\\Assets\\Data.csv", out numberOfLines);
int numOfOutputNeurons = CreatePointsUI(numberOfLines, dataValues);
//create layerSizes for example [2,3,2]
int[] layerSizes = new int[numberOfHiddenLayers + 2];
layerSizes[0] = (dataValues.Length / numberOfLines) - 1;
layerSizes[numberOfHiddenLayers + 1] = numOfOutputNeurons;
for (int i = 0; i < numberOfHiddenLayers; i++)
{
layerSizes[i+1] = Mathf.Max((dataValues.Length / numberOfLines) - 1, numOfOutputNeurons) + 1;
}
//create the actual matrices
List<float[,]> weights = new List<float[,]>();
List<float[]> biases = new List<float[]>();
MakeTheMatrices(layerSizes, out weights, out biases);
//fill weights with random values
RandomlyFillMatrices(weights);
//print matrices to make sure they're the right size and filled randomly
if (debugWeightMatrices)
Debug.Log(PrintMatrices(weights, "Weight Matrices"));
if (debugBiasMatrices)
Debug.Log(PrintMatrices(biases, "Bias Matrices"));
LineRenderer.GetComponent<DrawDecisionBoundary>().DrawLine(CreateDecisionBoundaryPoints(weights, biases, delta));
}
}
public struct OutputNeuronsAndColours
{
public string value;
public Color color;
public OutputNeuronsAndColours(string value, Color color)
{
this.value = value;
this.color = color;
}
}
public void DoTheWeightsStufUI(int weights)
{
int cwn = 0;
List<Transform> ws = new List<Transform>();
foreach (Transform child in weightsUI)
{
cwn++;
ws.Add(child);
}
int wta = weights - cwn;
for (int i = wta; i < 0; i++)
{
cwn--;
DestroyImmediate(ws[cwn].gameObject);
ws.RemoveAt(cwn);
}
for (int i = wta; i > 0; i--)
{
cwn++;
GameObject weight = Instantiate(textPrefab, weightsUI);
weight.GetComponentInChildren<TMP_Text>().SetText("W" + cwn.ToString());
}
}
public void DoTheBiasesStufUI(int biases)
{
int cbn = 0;
List<Transform> bs = new List<Transform>();
foreach (Transform child in biasesUI)
{
cbn++;
bs.Add(child);
}
int bta = biases - cbn;
for (int i = bta; i < 0; i++)
{
cbn--;
DestroyImmediate(bs[cbn].gameObject);
bs.RemoveAt(cbn);
}
for (int i = bta; i > 0; i--)
{
cbn++;
GameObject bias = Instantiate(textPrefab, biasesUI);
bias.GetComponentInChildren<TMP_Text>().SetText("B" + cbn.ToString());
}
}
string[] ReadData(string path, out int numberOfLines)
{
List<string> data_values = new List<string>();
StreamReader strReader = new StreamReader(path);
bool endOfFile = false;
int numOfLines = 0;
while (!endOfFile)
{
string data_string = strReader.ReadLine();
if (data_string == null)
{
endOfFile = true;
break;
}
else
numOfLines += 1;
data_values.AddRange(data_string.Split(','));
}
numberOfLines = numOfLines;
return data_values.ToArray();
}
int CreatePointsUI(int numberOfLines, string[] dataValues)
{
string[] possibleOutputs = new string[numberOfLines];
for (int i = 0; i < numberOfLines; i++)
{
possibleOutputs[i] = dataValues[(i * (dataValues.Length / numberOfLines)) + ((dataValues.Length / numberOfLines) - 1)];
}
List<OutputNeuronsAndColours> outputNeurons = new List<OutputNeuronsAndColours>(possibleOutputs.Length);
for (int i = 0; i < possibleOutputs.Length; i++)
{
bool contains = false;
for (int x = 0; x < outputNeurons.Count; x++)
{
if (possibleOutputs[i] == outputNeurons[x].value)
contains = true;
}
if (!contains)
outputNeurons.Add(new OutputNeuronsAndColours(possibleOutputs[i], new Color(UnityEngine.Random.Range(0f, 1f), UnityEngine.Random.Range(0f, 1f), UnityEngine.Random.Range(0f, 1f))));
}
for (int i = 0; i < numberOfLines; i++)
{
GameObject point = Instantiate(pointPrefab);
point.transform.position = new Vector2(float.Parse(dataValues[i * (dataValues.Length / numberOfLines)]), float.Parse(dataValues[(i * (dataValues.Length / numberOfLines)) + 1]));
foreach (OutputNeuronsAndColours value in outputNeurons)
{
if (value.value == dataValues[(i * (dataValues.Length / numberOfLines)) + ((dataValues.Length / numberOfLines) - 1)])
point.GetComponent<SpriteRenderer>().color = value.color;
}
}
return outputNeurons.Count;
}
public static void MakeTheMatrices(int[] layerSizes, out List<float[,]> weights, out List<float[]> biases)
{
List<float[,]> tempWeights = new List<float[,]>();
List<float[]> tempBiases = new List<float[]>();
for (int i = 0; i < layerSizes.Length - 1; i++)
{
tempWeights.Add(new float[layerSizes[i], layerSizes[i + 1]]);
}
for (int i = 1; i < layerSizes.Length; i++)
{
List<float> temp = new List<float>();
for (int x = 0; x < layerSizes[i]; x++)
temp.Add(0);
tempBiases.Add(temp.ToArray());
}
weights = tempWeights;
biases = tempBiases;
}
public static void RandomlyFillMatrices(List<float[,]> matrices)
{
foreach (float[,] matrix in matrices)
{
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int x = 0; x < matrix.GetLength(1); x++)
{
matrix[i, x] = UnityEngine.Random.Range(-3f, 3f);
}
}
}
}
public static string PrintMatrices(List<float[,]> matrices, string name = "Count")
{
string returnString = matrices.Count + " " + name;
foreach (float[,] matrix in matrices)
{
returnString += " (" + matrix.GetLength(0) + ", " + matrix.GetLength(1) + ")";
for (int i = 0; i < matrix.GetLength(0); i++)
{
string log = "";
if (i == 0)
log += "[";
else
log += " ";
for (int x = 0; x < matrix.GetLength(1); x++)
{
log += matrix[i, x];
if(x != matrix.GetLength(1) - 1)
log += " ";
}
if (i == matrix.GetLength(0) - 1)
log += "]";
Debug.Log(log);
}
}
return returnString;
}
public static string PrintMatrices(List<float[]> matrices, string name = "Count")
{
string returnString = matrices.Count + " " + name;
foreach (float[] matrix in matrices)
{
returnString += " (" + matrix.Length + ")";
string log = "[";
for (int i = 0; i < matrix.Length; i++)
{
log += matrix[i];
if (i != matrix.Length - 1)
log += " ";
}
log += "]";
Debug.Log(log);
}
return returnString;
}
private Vector3[] CreateDecisionBoundaryPoints(List<float[,]> weights, List<float[]> biases, float delta)
{
//check whether there are exactly 2 input neurons
if (weights[0].GetLength(0) != 2)
Debug.LogError("Not exactly 2 input neurons!");
//check whether there are exactly 2 output neurons
if (biases[biases.Count - 1].Length != 2)
Debug.LogError("Not exactly 2 output neurons!");
//create the values for the first layer
float[] weightsForFirstLayerX = new float[weights[0].GetLength(1)];
for (int i = 0; i < weights[0].GetLength(1); i++)
{
weightsForFirstLayerX[i] = weights[0][0, i];
}
float[] denominatorValuesFirstLayer = new float[weights[0].GetLength(1)];
for (int i = 0; i < weights[0].GetLength(1); i++)
{
denominatorValuesFirstLayer[i] = weights[0][1, i];
}
List<Vector3> pointsForGraph = new List<Vector3>();
//Calculate the y value(s) for each x with interval delta
for (float x = -.04f; x <= 1 + delta; x += delta)
{
float[] numeratorValuesFirstLayer = new float[weightsForFirstLayerX.Length];
for (int i = 0; i < weightsForFirstLayerX.Length; i++)
numeratorValuesFirstLayer[i] = x * weightsForFirstLayerX[i] + biases[0][i];
//get the row matrices for the decision boundary function
float[] numeratorResults = PassValuesThroughMatrices(numeratorValuesFirstLayer, weights, biases, true);
float[] denominatorResults = PassValuesThroughMatrices(denominatorValuesFirstLayer, weights, biases, false);
float y = (numeratorResults[1] - numeratorResults[0]) / (denominatorResults[0] - denominatorResults[1]);
pointsForGraph.Add(new Vector3(x, y, -1));
}
return pointsForGraph.ToArray();
}
private float[] PassValuesThroughMatrices(float[] values, List<float[,]> weights, List<float[]> biases, bool isNumerator)
{
float[] previousLayer = values;
//loop passing the previous layer values through the current layer: values = values * weights + biases
for (int i = 1; i < weights.Count; i++)
{
float[] temp = new float[weights[i].GetLength(1)];
//loop through the colums in the weight matrix
for (int v = 0; v < weights[i].GetLength(1); v++)
{
float value = 0;
//loop through the rows in the weight matrix
for (int b = 0; b < weights[i].GetLength(0); b++)
value += previousLayer[b] * weights[i][b, v];
if (isNumerator)
value += biases[i][v];
temp[v] = value;
}
previousLayer = temp;
}
//return the last itteration of values
return previousLayer;
}
}

Debug.Log() A 2D array from a custom class to main class

Here's my code.
CustomClass.cs
class ScoreBoard(){
private int m_lastCnt;
public ScoreBoard{
m_lastCnt = 0;
}
public void makeBoard(string history) {
string[] arrPartStr = history.Split(',');
int[] arrPart = new int[arrPartStr.Length];
for (int c = 0; c < arrPart.Length; c++)
{
int temp = 0;
if (arrPartStr[c][0] == 'P') temp = 100;
else if (arrPartStr[c][0] == 'B') temp = 200;
else temp = 300;
if (arrPartStr[c][1] == 'P') temp += 10;
if (arrPartStr[c][2] == 'P') temp += 1;
arrPart[c] = temp;
}
//var strTmp : String = strData;
//strTmp = "311|101|211|211|211|211|211|211|211|211|111|111|111|111|111|111|111|111|111"
//strTmp = strData.replace(/:/g,"");
int[,] arrTmp = new int[6100, 104];
}
}
Main Class i call the void method like this
ScoreBoard sb = ScoreBoard();
string history = "s ,o ,m ,e ,s ,t ,r ,i ,n ,g";
private void Start(){
sb.makeBoard(history);
}
How can i print my 2D array in my console?
I tried doing it like the for(int row){for(int col){}} but its not working i don't know why
Do you mean this?
for (int j = 0; j < arrTmp.GetLength(1); j++)
{
for (int i = 0; i < arrTmp.GetLength(0); i++)
{
var msg = "[" + i.ToString() + ", " + j.ToString() + "] = " + arrTmp[i, j].ToString();
Debug.Log(msg);
}
}
I got it to display:)
CustomClass.cs
int[,] arrTmp = new int[104, 6];
public int[,] GetBoard(){ return arrTmp }
MainClass.cs
int[,] arrayBigRoad = bsb.GetBoard();
for (int j = 0; j < arrTmp.GetLength(1); j++)
{
for (int i = 0; i < arrTmp.GetLength(0); i++)
{
var msg = "[" + i.ToString() + ", " + j.ToString() + "] = " + arrTmp[i, j].ToString();
Debug.Log(msg);
}
}
Thanks though Rodrigo . I'll mark yours as an answer

How to rescue this task?

I wonder how to do or write a code that it will print out no one got 20 points and it has to write a number of line. Everything works except if (is20 == false). How to fix it?
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
double[,] points = new double[50, 5];
Random r = new Random();
for (int k = 0; k < 50; k++)
{
for (int j = 0; j < 5; j++)
{
points[k, j] = r.NextDouble() * 5 + 15.5;
if (points[k, j] > 20) points[k, j] = 20;
Console.Write("{0:f1}", points[k, j]);
Console.Write(" ");
}
Console.WriteLine();
}
bestEstimated(points);
Console.ReadLine();
}
public static void bestEstimated(double[,] points)
{
bool is20 = false;
for (int line = 0; line < 50; line++)
{
for (int column = 0; column < 5; column++)
{
if (points[line, column] == 20)
{
Console.WriteLine("20 points got: " + line + " competitor");
is20 = true;
break;
}
}
}
if (is20 == false)
{
Console.WriteLine("No one got 20 points: ");
}
}
}
}
You can set is20=false in inner loop in else part and check it inside outer loop after inner loop.
public static void bestEstimated(double[,] points)
{
bool is20 = false;
for (int line = 0; line < 10; line++)
{
for (int column = 0; column < 5; column++)
{
if (points[line, column] == 20)
{
Console.WriteLine("20 points got: " + line + " competitor");
is20 = true;
break;
}
else
{
is20=false;
}
}
if (!is20)
{
Console.WriteLine("20 points not got: " + line + " competitor");
}
}
if(is20 == false)
{
Console.WriteLine("No one got 20 points: ");
}
}
Just a wild guess from your comments below your question:
public static void bestEstimated(double[,] points)
{
var not20Points = new List<int>();
for (int line = 0; line < 50; line++)
{
bool is20 = false;
for (int column = 0; column < 5; column++)
{
if (points[line, column] == 20)
{
Console.WriteLine("20 points got: " + line + " competitor");
is20 = true;
break;
}
}
if (is20 == false)
{
Console.WriteLine("competitor" + line + " didnt get 20 points"); //also can print it here if ya want...
not20Points.Add(line);
}
}
if (not20Points.Count == 50)
{
Console.WriteLine("No one got 20 points");
}
else
{
Console.WriteLine("Those lines did get 20 points: " + string.Join(",", Enumerable.Range(0, 50).Except(not20Points)));
Console.WriteLine("Those lines didnt get 20 points: " + string.Join(",", not20Points));
}
}
(Updated my version, to only print stuff if atleast one column has 20 points)

C# Scoping or similar error? Expected number of coin tosses for a specified sequence to appear

This program calculates the expected number of toin cosses until a given sequence will appear. The formula sums powers of two, where powers are those k for which the first k elements of the sequence match the last k elements, in order.
My question is why, when I test it with two different sequences, it only returns one result twice. I assume that it is doing exactly what it looks like and overwriting test1 with test4 when test4 is instanciated, but this code looks to me to be similar to code from smaller exercises that did not have this overwriting behaviour.
This is my second programming course, and my first in C#, neither has been in my mother tongue, so I might be a bit slow with some of the concepts.
I suspect this has to do with one of the lines with public static... (I am not sure how to refer to them) or maybe a protection level. The expectation for test1 should be 38 (2 + 2^2 + 2^5).
using System;
namespace CSProject
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Expectation tests");
PlayerSequence test1 = new PlayerSequence("bc00100");
PlayerSequence test4 = new PlayerSequence("101101");
Console.WriteLine("Expectation of test1 bc00100");
Console.WriteLine (test1.Expectation ());
Console.WriteLine("Expectation of test4 101101");
Console.WriteLine(test4.Expectation());
}
}
class PlayerSequence
{
//ATTRIBUTES
private static bool[] sequence;
//CONSTRUCTORS
public PlayerSequence()
{
}
public PlayerSequence(string sequence_String)//Seems to work!!
{
char[] sequence_array = sequence_String.ToCharArray();
int inputLength = sequence_array.Length;
int sequence_length = 0;
for( int i = 0; i < inputLength; i++) {
if (sequence_array[i] == '1' || sequence_array[i] == '0') {
sequence_length++;
}
}
sequence = new bool[sequence_length];///KEYItem
int input_index_adjustment = 0;
for (int i = 0; i < inputLength; i++) {
int sVal;
if (!Int32.TryParse(sequence_String[i].ToString(), out sVal))
{
input_index_adjustment++;
continue;
}
if (sVal == (Int32)1)
PlayerSequence.sequence[i - input_index_adjustment] = true;
if (sVal == (Int32)0)
PlayerSequence.sequence[i - input_index_adjustment] = false;
if(sVal != 1 && sVal != 0)
input_index_adjustment++;
}
}
public override string ToString()//Works
{
string retString;
retString = "";
for (int i = 0; i < sequence.Length;i++) {
if (sequence[i] == true) retString = retString + "T ";
else retString = retString + "H ";
}
return retString;
}
public ulong Expectation(){
ulong espTA = 0;
for (int kexp = 0; kexp < /*PlayerSequence.*/sequence.Length; kesp++)
{
if(SeqCheck(sequence,kesp+1))
expTA = expTA + (ulong)Math.Pow(2, kexp+1);
}
return espTA;
}//end Expectation
public static bool SeqCheck(bool[] toCheck, int k){
//Test of required property for each power of 2 here k
int a = toCheck.Length ;
bool seqgood = false;
bool[] checkStart = new bool[k];
bool[] checkEnd = new bool[k];
for (int i = 0; i < k; i++) {//loop sets up subarrays to compare
checkStart[i] = toCheck[i];
checkEnd[i] = toCheck[a - k + i];
}
for (int i = 0; i < k; i++){//loop does comparison
if(checkStart[i] != checkEnd[i])
{
seqgood = false;
break;
}
seqgood = true;
}
return seqgood;
}//end SeqCheck
}//end PlayerSequence class
}//End this section of the namespace
It is your use of the static keyword for the local variable in your class. By doin so, you make the variable a part of the type (PlayerSequence) and not the instance of PlayerSequence (test1, test4). Below worked on my machine.
class PlayerSequence
{
//ATTRIBUTES
private bool[] sequence;
//CONSTRUCTORS
public PlayerSequence()
{
}
public PlayerSequence(string sequence_String)//Seems to work!!
{
char[] sequence_array = sequence_String.ToCharArray();
int inputLength = sequence_array.Length;
int sequence_length = 0;
for (int i = 0; i < inputLength; i++)
{
if (sequence_array[i] == '1' || sequence_array[i] == '0')
{
sequence_length++;
}
}
sequence = new bool[sequence_length];///KEYItem
int input_index_adjustment = 0;
for (int i = 0; i < inputLength; i++)
{
int sVal;
if (!Int32.TryParse(sequence_String[i].ToString(), out sVal))
{
input_index_adjustment++;
continue;
}
if (sVal == (Int32)1)
sequence[i - input_index_adjustment] = true;
if (sVal == (Int32)0)
sequence[i - input_index_adjustment] = false;
if (sVal != 1 && sVal != 0)
input_index_adjustment++;
}
}
public override string ToString()//Works
{
string retString;
retString = "";
for (int i = 0; i < sequence.Length; i++)
{
if (sequence[i] == true) retString = retString + "T ";
else retString = retString + "H ";
}
return retString;
}
public ulong Expectation()
{
ulong espTA = 0;
for (int kexp = 0; kexp < sequence.Length; kexp++)
{
if (SeqCheck(sequence, kexp + 1))
espTA = espTA + (ulong)Math.Pow(2, kexp + 1);
}
return espTA;
}//end Expectation
public bool SeqCheck(bool[] toCheck, int k)
{
//Test of required property for each power of 2 here k
int a = toCheck.Length;
bool seqgood = false;
bool[] checkStart = new bool[k];
bool[] checkEnd = new bool[k];
for (int i = 0; i < k; i++)
{//loop sets up subarrays to compare
checkStart[i] = toCheck[i];
checkEnd[i] = toCheck[a - k + i];
}
for (int i = 0; i < k; i++)
{//loop does comparison
if (checkStart[i] != checkEnd[i])
{
seqgood = false;
break;
}
seqgood = true;
}
return seqgood;
}//end SeqCheck
}

How do I convert split string (string array) to double in C#?

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();
}
}

Categories

Resources