What will be the output of the following C++ code? [code] #include <iostream> #include <ctime> #include <cstdlib> using

What will be the output of the following C++ code?
Code:
    #include <iostream>
    #include <ctime>
    #include <cstdlib>
    using namespace std;
    int main()
    {
        srand((unsigned)time(0));
        int ran;
        int low = 1, high = 10;
        int range = (high - low) + 1;
        for(int index = 0; index < 1; index++)
        {
            ran = low + int(range * rand() / (RAND_MAX + 1.0));
            cout << ran << endl;
        }
    }
A. 1
B. 2
C. 3
D. 4
 
Answer: a
Explanation: In this program the output will always be 1 because as one can observe from the formula used in line #13 that the term inside int() will always be zero. Hence the output will always be 1.
Output:
Code:
$ g++ rand4.cpp
$ a.out
1
 

Tìm kiếm

Back
Top