Question:
Why won't this work? C#?
Chris
2013-08-15 16:35:55 UTC
Can someone explain to me why:

static void Main(string[] args)
{
int x = 1;
int z = 2;
int ar = 0;
string[] prime = new string[ar];

while (x <= 99)
{
z = 2;
while (z <= 9)
{
var y = (x/z);
Console.WriteLine(y);
if (y.GetType() == typeof(double))
{
prime[ar] = x.ToString();
ar ;
Console.WriteLine(x " is a prime!");
}
z ;
}
x ;
Console.WriteLine(x);
}
File.WriteAllLines(@"C:\users\chris\desktop\primeornot.txt", prime);
Console.ReadLine();
}

Fails to find a prime number? What this code does is check to see if the division came out as a whole number, or a decimal, and if it came out as a decimal, put it inside an array.
Three answers:
Ratchetr
2013-08-15 16:59:44 UTC
The expression x/z will always be an int (a whole number).

When you divide 2 integers in C#, the result is always an int. The remainder gets discarded.



Use the mod (%) operator instead of division. Check for x % z being 0.



Also, your prime array is size 0. You will get an error when you try to assign a value to it.
husoski
2013-08-16 00:17:27 UTC
You can't resize arrays. You declare prime to be an array of zero (0) strings with new string[a4], executed at a time when ar==0. That's the same as new string[0]. An empty array. Any attempt to read or write anything will throw an exception.



If you're brand new to C#, simply allocate prime = new String[100] or somthing definitely big enough to hold all the primes you'll find.



If you want a data type to hold a growing array of Strings, add a using for System.Collections.Generic and use the List type. Docs for that can be found at:

http://msdn.microsoft.com/en-us/library/6sh2ey19%28v=vs.100%29.aspx



It's unusual to use string format for a list of prime numbers,though. Integer types are easier to manipulate, and just as easy to print out when a string representation is needed. In most cases, that conversion is automatic, but if you need to convert from string to a numeric format then you will ALWAYS need a method call.
?
2013-08-16 00:04:13 UTC
You declared prime with an index of 0. Therefore no value is set and it is still null.



To fix this switch your ar variable set to a number greater than 0. ex. int ar = 1;



Another problem exists where you have int. Integers are always 0,1,2,3,4.

You are looking to use a float value. These can hold decimal values.



Usage is like this:



float example = 2.8F;

or

float example;

example = 0.5F;

or

float example = 0;

example++;



Any further help after that you can contact me by email.



- http://answers.yahoo.com/ Freelance developer question answerer

- Souly helping to follow Jesus and help novice coders!

- If you need help or want to learn some email me!

- I teach Java, HTML, CSS, JavaScript (Email me I teach all)


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Continue reading on narkive:
Loading...