
August 30th, 2017, 04:48 PM
#1
Review, divide two integers
Problem: "Write a valuereturning function called isFactor. It should take 2 integer parameters and return true if the 2nd number can be divided by the 1st number evenly (in other words, if it has no remainder). So isFactor(4, 16) should return true because 16/4 = 4, but isFactor(4, 15) should return false because 15/4 = 3.75. Test it in int main()."
When I debug my code I get" error C4716: 'divide': must return a value", but I do not understand why I am getting that error.
Code:
bool divide(int x, int y)
{
int rest = x / y;
if (rest == 0)
cout << "True" << endl;
else
cout << "False" << endl;
}
// main function
int main()
{
int x;
int y;
//prompts user for input
cout << "Input first value: " << endl;
cin >> x;
cout << "Input second value: " << endl;
cin >> y;
if
(divide(x, y) == true)
cout << y << "can be divided by " << x << endl;
else
cout << y << "can not be divided by " << x << endl;
return 0;
}

August 30th, 2017, 05:31 PM
#2
Re: Review, divide two integers
Originally Posted by TheJollyRoger
When I debug my code I get" error C4716: 'divide': must return a value", but I do not understand why I am getting that error.
It's because you have declared the divide function to return a bool but it doesn't return anything.
You print a message to cout in divide but that's not the same as returning something. For that you need to use a return statement.
Last edited by wolle; August 30th, 2017 at 05:35 PM.

August 30th, 2017, 05:34 PM
#3
Re: Review, divide two integers
It's because your divide function in not returning a value.
Code:
bool divide(int x, int y)
{
if (x % y == 0)
return true;
else
return false;
}

August 30th, 2017, 05:45 PM
#4
Re: Review, divide two integers
Thanks. Now I've fixed that issue.

August 31st, 2017, 12:50 AM
#5
Re: Review, divide two integers
Originally Posted by TheJollyRoger
Thanks. Now I've fixed that issue.
Note that there's a distinction between integer types and floating point types in C++. Make sure you fully understand this distinction and the implications.
Regarding integer division. This,
Code:
int rest = x / y; // / gives quotient
will give you the quotient (not the rest) of x divided by y. This,
Code:
int rest = x % y; // % gives remainder
will give you the remainder (the rest) of x divided by y. if it is 0 then x is evenly divisible by y. That's what you should use in isFactor().
Last edited by wolle; August 31st, 2017 at 01:04 AM.
Tags for this Thread
Posting Permissions
 You may not post new threads
 You may not post replies
 You may not post attachments
 You may not edit your posts

Forum Rules

Click Here to Expand Forum to Full Width
OnDemand Webinars (sponsored)
