In my program, I think my count variable is not holding the value. What do I do so that it can hold? here`s my code.
static void Main(string[] args)
{
double a;
double count = 0;
Console.WriteLine("Enter the Numbers : 开发者_C百科");
for (double i = 1; i <= 10; i++)
{
a = Convert.ToDouble(Console.ReadLine());
if (a % 2 != 0 || a % 3 != 0 || a % 5 != 0)
{
count = count++;
}
//else
//{
// }
Console.ReadLine();
}
Console.WriteLine("The Numbers That Are divisible by 2,3,5 are : " + count);
Console.ReadLine();
}
Your mistake is the line count = count++;
. This does not increase count
by one. You need to use just count++;
.
The expression count++
will increment the value of count
by one and then return as the expression's value the original value of count. In this case the increment of count++
happens before the assignment, so count
is first incremented by one, but then you assign the value of count++
, that is, the original value, to count
again, so it does not increase at all.
Your program lists numbers that are not divisible by any of those numbers. If you want to count numbers which aren't divisible by all of them then you need to use if (a % 2 != 0 && a % 3 != 0 && a % 5 != 0)
instead. I would also suggest using integers instead of doubles if possible.
Finally, your print statement says numbers that are divisible by 2,3,5, but count is the number of numbers which are not divisible by those numbers.
Edit: Are you entering 10 numbers each time you test? I'm not sure what kind of result you will get if you give a blank input.
Not to add to what jk and David Kanarek said in their answers or what the others the comments on those answers, As pointed out by jk use count+1 instead of count ++ , also a few notes:
1) Your using console.Readline() twice in the loop, so the user will enter 20 inputs but only 10 will be read..
2) Just alittle extra thought on Anton's comment, in your if clause , if you use || your trying to catch any of the conditions being true, in other words:
// a=2
if (a % 2 != 0 || a % 3 != 0 || a % 5 != 0) // False || True || True = True
{
count = count + 1 ;// count will increase
}
on the other hand, using && :
// a=2
if (a % 2 != 0 && a % 3 != 0 && a % 5 != 0) // False && True && True = false
{
count = count + 1 ; //count will not increase
}
A useful Link explaining operators
精彩评论