Consider the following statements: double num1, num2, num3; int int1, int2, int3
ID: 3688930 • Letter: C
Question
Consider the following statements:
double num1, num2, num3;
int int1, int2, int3;
int value;
num1 = 5.0; num2 = 6.0; num3 = 3.0;
int1 = 4; int2 = 7; int3 = 8;
and the function prototype:
double cube(double a, double b, double c);
Which of the following statements are valid? If they are invalid, explain why.
a. value = cube (num1, 15.0, num3);
b. cout << cube(num1, num3, num2) << endl;
c. cout << cube(6.0, 8.0, 10.5) << endl;
d. cout << cube(num1, num3) << endl;
e. value = cube(num1, int2, num3);
f. value = cube(7, 8, 9);
g. value = cube(int1, int2, int3);
Explanation / Answer
a. value = cube (num1, 15.0, num3);
This is a valid statement
As per the prototype provided for the function cube, the the function accepts 3 double parameters and returns a double.
When the above statement is executed, the function tries to assign a double value to a variable 'value' which is of type int.
For example if cube (num1, 15.0, num3) returns 1.2345, it is supposed that the value of 'value' is also 1.2345, but here since 'value' is an integer variable it takes only 1 and discards the decimals.
If we try to print value, instead of 1.2345 it prints only 1.
b. cout << cube(num1, num3, num2) << endl;
This is a valid statement.
c. cout << cube(6.0, 8.0, 10.5) << endl;
This is a valid statement.
d. cout << cube(num1, num3) << endl;
This is an invalid statement.
As per the prototype provided for the function cube, the the function accepts 3 double parameters and returns a double. But here we are providing only 2 input parameters hence it throws an error stating "'cube':function does not take 2 arguments"
e. value = cube(num1, int2, num3);
This is a valid statement.
Here in this case int2 is a variable of type int, as the function takes parameters of type double, it converts int2 to double i.e., here int2=7, when the function is executed it takes the value as 7.0 which is the same. But the result is a double and is assigned to int. If the result of the function is 1.2345, the value in variable 'value' will be only 1.
f. value = cube(7, 8, 9);
This is a valid statement. Converts 7,8,9 to 7.0,8.0,9.0 respectively and continues the execution.
g. value = cube(int1, int2, int3);
This is a valid statement. This is also the same as above, we are given int1=4, int2=7, int3=8, when the above statement is executed it converts the values to double i.e, 4.0, 7.0 and 8.0 and while assinging the result to 'value' it discards the decimal part of the result obtained and takes in only integer value.