Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want to be able to determine what the value is selected when I get a random number in windows forms.
For example, int mynum = numbers[rand.Next(0,7)];
I know the range is between 0 and 7, but I want to be able to identify what number is selected. e.g. numbers[3]
The following is the code I have. I have read binary values into an array int [] numbers and passed it through the following method. It generates my random 3 bit binary value, but I am making a small quiz where the number identified is the value the random number selects (e.g. the location 3 is the correct value for the item stored there, numbers[i] ==answer).
Is there a way to access this value?
public void generateBinary3bit(int[] numbers, Form1 f1)
{
Random rand = new Random();
int mynum = numbers[rand.Next(0,7)];
**int ans = numbers[rand];**
f1.lblBinaryText.Text = mynum.ToString();
}
For context, I am reading in the values into the array here:
int [] numbers = new int[8];
public void readNumbers(int[]numbers, Form1 F1)
{
try
{
StreamReader sr = new StreamReader(#"C:\BinaryNumbers.csv");
while(sr.ReadLine() !=null)
{
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = Convert.ToInt32(sr.ReadLine());
answer = i;
}
}
sr.Close();
}
catch ( Exception e)
{
}
}
Thank you,
Just assign some variable to the result of the rand.Next() before using it in the array:
Random rand = new Random();
int randIndex = rand.Next(0,7);
int mynum = numbers[randIndex];
and you are good to go.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I was trying to raise a number to a power using a for loop. However, when I wrote this and ran it, it gave me a random number.
using System;
class Program {
static void Main(string[] args) {
var a = 5;
for(int i=0; i<5; i++){
a*=a;
}
Console.WriteLine(a);
}
}
Why is it that this doesn't work? Is a copied only once and can't be used this way?
You can multiply by itself but you can not display result because you overflowing integer (exceed int32 size)(var by default in this case is int32).
Your results :
25
625
390625
out of range (exceeded size).
Answer for you question should be:
var initialValue = 2;
var exponent = 4;
var power = initialValue;
for (int i = 0; i < exponent ; i++)
{
initialValue *= power;
}
OR
var exponentiation = Math.Pow(2, 5);
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I need to access an element from an array and I am getting this error right here Console.WriteLine(testChoice[0]);
Why is this happening? Here is my code:
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] m1 = { 100 };
int a = m1.ElementAtOrDefault(0);
Console.WriteLine("Type m1 underneath");
string test;
test = Console.ReadLine();
int testChoice;
testChoice = Convert.ToInt32(test);
for (int i = 0; i < 1; i++)
{
Console.WriteLine(testChoice[0]);
}
}
}
The variable which index you are trying to access, testChoice, is not an array. It is an int variable. To print it just get rid of the for loop and the index:
static void Main()
{
int[] m1 = { 100 };
int a = m1.ElementAtOrDefault(0);
Console.WriteLine("Type m1 underneath");
string test;
test = Console.ReadLine();
int testChoice;
testChoice = Convert.ToInt32(test);
Console.WriteLine(testChoice);
}
To access an array element by user input:
//class variable
private static int _testChoice;
static void Main()
{
int[] testChoices = { 100, 200, 300 };
//int a = m1.ElementAtOrDefault(0);
//Console.WriteLine("Type m1 underneath");
string indexInput;
Console.WriteLine("Please specify the index:");
indexInput = Console.ReadLine();
int index;
index = Convert.ToInt32(indexInput );
_testChoice = testChoices[index];
Console.WriteLine(_testChoice);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am making a program that finds the area of square. The calculation is done on another class. I have to use an array with values 1-10. I have to find the squares of those numbers in the array using the property from the other class. I am confused on how to do that. This is what I have done so far.
using System;
using Square;
namespace DemoSquares
{
public class DemoSquares
{
static void Main()
{
int[] numbers = new int[10];
Squares asquare = new Squares();
asquare.Length = numbers[0];
foreach (int i in numbers)
{
Console.WriteLine("{0}", i, asquare.Area);
}
}
}
}
This is the class.
using System;
namespace Square
{
class Squares
{
private int length;
private int area;
public int Length
{
get
{
return length;
}
set
{
length = value;
CalcArea();
}
}
public int Area
{
get
{
return area;
}
}
private void CalcArea()
{
area = Length * Length;
}
}
}
First populate the array with some values, possibly something like this:
int[] numbers = new int[10];
int counter = 1;
for (int i = 0; i < numbers.Length; i++) {
numbers[i] = counter;
counter++;
}
then you can find the area of each square like so:
foreach (int i in numbers)
{
Squares asquare = new Squares();
asquare.Length = i;
Console.WriteLine("{0}", i, asquare.Area);
}
Another alternative
int[] numbers = {
1,2,3,4,5,6,7,8,9,10 // enter your numbers here
};
numbers.ToList().ForEach(n => {
Squares asquare = new Squares();
asquare.Length = n;
Console.WriteLine("{0}", n, asquare.Area);
});
note - if you decide to go with the latter, ensure you import:
using System.Linq;
I'am not shure if I understand you but this may work:
foreach (int i in numbers)
{
asquare.Length = i;
asquare.CalcArea();
Console.WriteLine("Area for {0}: {1}", i, asquare.Area);
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
static void Main(string[] args)
{
int[] hours = new int[30];
const decimal HOURLY_RATE = 2.5M;
const decimal MAX_FEE = 20.00M;
decimal pay;
double average;
int counter = 0;
string line;
StreamReader fileSR = new StreamReader("hours.txt");
line = fileSR.ReadLine();
while (line != null)
{
hours[counter] = int.Parse(line);
counter = counter + 1;
line = fileSR.ReadLine();
}
fileSR.Close();
Console.WriteLine("Hours Parking Fee");
for (int i = 0; i < hours.Length; i++)
{
pay = Math.Min(hours[i] * HOURLY_RATE, MAX_FEE);
Console.WriteLine("{0,4} {1,10}", hours[i], pay.ToString("C"));
}
Console.ReadKey();
}
}
As said, I don't have a clue on how to work out the average from a txt file using StreamReader. It would be great if I could have some help. Feel free to edit the code as much as you want to make it work.
At the moment the code outputs into a console application, showing the Hours, and the Parking Fee. But under that I want it to say the average of the Parking Fee.
Using StreamReader is irrelevant in this case. What you are doing now is filling an array with the values from the file. These values are stored in hours array.
From here, the easiest way would be to take the average from that array:
double sum = 0;
for (int i = 0; i < hours.Length; i++)
{
sum += hours[i];
}
double average = sum/hours.Length;
or something similar to that, for example with LINQ directly:
using System.Linq;
// ...
double average = hours.Average();
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
So I'm trying to make a battleship game, generating random position of ships at beginning. I'm using a array of integers to keep track of where are the ships. I wish to generate a random sequence of numbers with given argument of how much numbers. Say i want 4 numbers, which are all in sequence like 1,2,3,4 but I can also randomly get 55,56,57,58 ? Any ideas? 4 numbers would represent aircraft carrier, 3 destroyer etc etc..
As others have pointed out, this won't actually help much in Battleship where ships can be placed in different directions, but to answer the question you asked, just generate one random number and then increment.
private static Random _random = new Random();
private static IEnumerable<int> GetSequence(int size, int max)
{
var start = _random.Next(max - (size - 1));
for (var i = 0; i < size; i++)
{
yield return start + i;
}
}
Edit: As #EricLippert mentions, this can be shortened to:
private static Random _random = new Random();
private static IEnumerable<int> GetSequence(int size, int max)
{
return Enumerable.Range(_random.Next(max-(size-1)), size);
}
private static Random rand = new Random();
static void Main(string[] args)
{
int[] numbers = RandomNumbers(4, 1, 100);
Console.WriteLine(string.Join(",",numbers));
Console.Read();
}
public static int[] RandomNumbers(int numberOfResults, int minValue, int maxValue)
{
// declare array for return values
int[] result = new int[numberOfResults];
// get next value from random passing in the min and max ranges
int start = rand.Next(minValue, maxValue);
// generate the numbers up to the max number of results required
for (int i = 0; i < numberOfResults; i++)
{
result[i] = start++;
}
return result;
}