Why am I getting an error message of "Error 1 Division by constant zero 25 17 ConsoleApplication3"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Higher, Lower... What is the highest possible number that you're thinking of?");
string b = Console.ReadLine();
int f = int.Parse(b);// F = THE MAX #
Random computerguess = new Random();
int computerGuess = computerguess.Next(f);
Console.WriteLine(computerGuess);
Console.WriteLine("if your number is higher than the number displaid above, then press the '1' key so I guess higher. if your number is lower press the '0' (down) as in telling the comp to go down/lower");
string开发者_StackOverflow中文版 I = Console.ReadLine();
int G = int.Parse(I);
int H = 1/2;
if (G == 0)
{
computerGuess = computerGuess * H;
Console.WriteLine(computerGuess);
}
Console.Read();
}
}
}
You are doing an integer division:
int H = 1/2;
This will be zero always. Instead use a decimal:
decimal H = 0.5M;
and then cast your computerGuess
back to int:
..
computerGuess = (int)(computerGuess * H);
Because
int H = 1/2;
sets H to 0: 0.5 rounded down to the nearest integer.
I don't get that error message when I try to compile your code.
The error message might be a bit misleading. This is line 25, that doesn't actally divide by zero:
int H = 1/2;
You are dividing integers, so the result will be zero. This calculation is done by the compiler, so the code generated is equivalent to:
int H = 0;
You probably get a warning because the result is most likely not the intended.
About the line...
int H = 1/2;
You are triying to store the float value 0.5 inside a Integer var.
精彩评论