c表达式没有给出正确的输出

时间:2018-04-17 19:02:38

标签: c getopt integer-division atoi

int main (int argc, char **argv)
{
    int aflag = -1;
    int bflag = -1;
    int cvalue = -1;
    int index;
    int c;
    int arotate = -1;
    int tran = -1;
    int acc;


    opterr = 0;
    printf("top of the program\n");

    while ((c = getopt (argc, argv, "r:t:s:")) != -1) {
        printf("top of the loop\n");
        switch (c)
        {
        case 'r':
            printf("here under r\n");
            aflag = atoi(optarg);
            break;
        case 't':
            printf("here under t\n");
            bflag = atoi(optarg);
            break;
        case 's':
            printf("here under s\n");
            cvalue = atoi(optarg);
            break;
        default:
            abort ();
        }
    }
    arotate = ((1/2) * (60/aflag))* 1000;
    tran = ((60/aflag) * (1/cvalue)) * 1000;
    acc = bflag + arotate + tran;

    printf("aflag = %d, bflag = %d, cvalue = %d\n, arotate = %d\n, tran = "
        "%d\n, acc = %d\n",aflag, bflag, cvalue, arotate, tran, acc);
    return 0;
}

当我运行一切正常但arotate和tran总是= 0.我希望检查./a.out -r 15000 -t 4 -s 800 answer 6.005ms。它必须是我在这里做错的事情

arotate = ((1/2) * (60/aflag))* 1000;
tran = ((60/aflag) * (1/cvalue)) * 1000;
acc = bflag + arotate + tran;

arotate = 0tran = 0,它们应该是2和.005。但acc似乎正在工作,因为我得到了4。

1 个答案:

答案 0 :(得分:3)

所有算术运算都是在整数值上完成的,因此每个子表达式的结果也是一个整数,并将结果赋值为整数。您正在经历截断结果值。

arotatetranacc更改为double,将相应的输出说明符从%d更改为%f,然后更改表达式中的常量为浮点常量(即包含小数分量)。

 double arotate = -1;
 double tran = -1;
 double acc;

 ...

arotate = ((1.0/2.0) * (60.0/aflag))* 1000.0;
  tran = ((60.0/aflag) * (1.0/cvalue)) * 1000.0;
  acc = bflag + arotate + tran;


printf ("aflag = %d, bflag = %d, cvalue = %d\n, arotate = %f\n, tran = %f\n, acc = %f\n", 
         aflag, bflag, cvalue, arotate, tran, acc);