string strConn1 = " provider=Microsoft.Jet.OLEDB.4.0;Data Source=hotel.mdb" ;
OleDbConnection myConn1 = new OleDbConnection (strConn1) ;
myConn1.Open();
string str1="select COUNT(*) from hotel ";
string str11="select COUNT(h_empty) from hotel where h_empty='未登记'";
string str12="select COUNT(h_empty) from hotel where h_empty='已登记'";
//总房间数
OleDbCommand Com1=new OleDbCommand(str1,myConn1);
int n1=(int)Com1.ExecuteScalar();
//已登记房间数
OleDbCommand Com12=new OleDbCommand(str12,myConn1);
int n12=(int)Com12.ExecuteScalar();
//未登记房间数
OleDbCommand Com11=new OleDbCommand(str11,myConn1);
int n11=(int)Com11.ExecuteScalar();
textBox1.Text=Convert.ToString(n12/n1);
textBox2.Text=Convert.ToString(n11/n1);
myConn1.Close();运行结果是;textBox1值是0
textBox2值是0
为什么呢?
谢谢了
n1>n11;n1>n12
int型的做除法原則:除法值大於0.5則為1小於則為0
所以n11/n1<0.5 =0
n12/n1<0.5 =0
我建议lz调试一下先,看看到底是哪里出了问题,你的cast只是以下5个地方在用,要出现invalidcastexception就这些地方了
int n1=(int)Com1.ExecuteScalar();
int n12=(int)Com12.ExecuteScalar();
int n11=(int)Com11.ExecuteScalar();
textBox1.Text=Convert.ToString(n12/n1);
textBox2.Text=Convert.ToString(n11/n1);我不知道select count(*)在access里面到底会返回什么类型,sqlserver当然是int,oracle很可能返回一个long(number类型)所以还是调试一下,看看到底是什么类型先
string strConn1 = " provider=Microsoft.Jet.OLEDB.4.0;Data Source=hotel.mdb" ;
OleDbConnection myConn1 = new OleDbConnection (strConn1) ;
myConn1.Open();
string str1="select COUNT(*) from hotel ";
string str11="select COUNT(h_empty) from hotel where h_empty='未登记'";
string str12="select COUNT(h_empty) from hotel where h_empty='已登记'";
//总房间数
OleDbCommand Com1=new OleDbCommand(str1,myConn1);
int n1=(int)Com1.ExecuteScalar();
//已登记房间数
OleDbCommand Com12=new OleDbCommand(str12,myConn1);
int n12=(int)Com12.ExecuteScalar();
//未登记房间数
OleDbCommand Com11=new OleDbCommand(str11,myConn1);
int n11=(int)Com11.ExecuteScalar();
// textBox1.Text=Convert.ToString(n12/n1);
textBox1.Text=Convert.ToString(n12 * 1.0 / n1);
// textBox2.Text=Convert.ToString(n11/n1);
textBox2.Text=Convert.ToString(n11 * 1.0 / n1);
myConn1.Close();
textBox1.Text=Convert.ToString(n12 * 1.0 / n1);
textBox2.Text=Convert.ToString(n11 * 1.0 / n1);
为什么要n11*1.0?
n12 / n1 因为n12小于n1,所以int除法结果为0
n12 * 1.0 / n1
乘以1.0后将int自动转换为float进行计算,返回正确结果