This question already has answers here:
Closed last year.
Simpliest operation in C not working [duplicate]
(5个答案)
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回答6.005m s。这一定是我做错了什么
arotate = ((1/2) * (60/aflag))* 1000;
tran = ((60/aflag) * (1/cvalue)) * 1000;
acc = bflag + arotate + tran;

arotate = 0tran = 0它们应该是2和.005。但是当我4岁的时候,acc似乎在工作。

最佳答案

所有的算术运算都是对整数值执行的,因此每个子表达式的结果也是一个整数,并将结果赋给一个整数。结果值被截断。
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);

10-08 05:10