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
为什么呢?
谢谢了

解决方案 »

  1.   

    把int換成long類型。分析:
        n1>n11;n1>n12
    int型的做除法原則:除法值大於0.5則為1小於則為0
    所以n11/n1<0.5 =0
    n12/n1<0.5 =0
      

  2.   

    我试了,还是不行啊,提示错误:未处理的“System.InvalidCastException”类型的异常出现在 WindowsApplication1.exe 中。其他信息: 指定的转换无效。
      

  3.   

    Convert.ToDouble(n12)/Convert.ToDouble(n1)
      

  4.   

    没有使用过access
    我建议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类型)所以还是调试一下,看看到底是什么类型先
      

  5.   

    n12 比 n1 小,n12/n1 的结果一定是0啊
      

  6.   

    //以下调试通过
    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();
      

  7.   

    谢谢各位的热心帮助,调试已经成功了,但我还是有点不明白,
    textBox1.Text=Convert.ToString(n12 * 1.0 / n1);
    textBox2.Text=Convert.ToString(n11 * 1.0 / n1);
    为什么要n11*1.0?
      

  8.   

    关于 “为什么要n11*1.0?”
    n12 / n1 因为n12小于n1,所以int除法结果为0
    n12 * 1.0 / n1
    乘以1.0后将int自动转换为float进行计算,返回正确结果
      

  9.   

    n12 * 1.0 / n1 的结果是double,不是float,因为1.0是double