除法产生整数C ++

时间:2013-11-24 18:34:26

标签: c++ function random

我使用rand函数生成两个随机数,分子和分母,用于除法,有时结果是float,有时是整数。如何只生成整数结果?这是我的代码:

  srand(time(NULL)); 

integer1 = ((rand() % ( 81 - 5 ) + 5 )*2);
integer2 = ((rand()%3 + 1)*2); 
answer = integer1/integer2;

do {
    cout << "How much is " << integer1 << " divided by " << integer2 << " ? : " << endl;
    cin >> answer;

    if (answer == integer1/integer2) {
        cout << "Very Good !"<< endl;
    }
    else {
        cout << "Your answer is false, please try again !"<<endl;
    }

} while ((integer1/integer2!=answer));

1 个答案:

答案 0 :(得分:0)

如果/的两个操作数都是整数类型,则结果将是整数。如果任一操作数是浮点类型,则结果将是浮点类型。如果你想要它是一个截断的整数,你需要转换为你想要的类型。

相关问题