Why do I get the error "Floating point exception"? - c++

I am trying to write a code that finds perfect numbers lower than the user's input.
Sample of correct output:
Enter a positive integer: 100
6 is a perfect number
28 is a perfect number
There are no more perfect numbers less than or equal to 100
But when I run my code, I get the error Floating point exception
and can not figure out why. What am I doing wrong?
Here is my code:
#include <iostream>
using namespace std;
bool isAFactor(int, int);
int main(){
int x, y;
int countOut, countIn;
int userIn;
int perfect = 0;
cout << "Enter a positive integer: ";
cin >> userIn;
for(countOut = 0; countOut < userIn; countOut++){
for(countIn = 1; countIn <= countOut; countIn++){
if(isAFactor(countOut, countIn) == true){
countOut = countOut + perfect;
}
}
if(perfect == countOut){
cout << perfect << " is a perfect number" << endl;
}
perfect++;
}
cout << "There are no more perfect numbers less than or equal to " << userIn << endl;
return 0;
}
bool isAFactor(int inner, int outer){
if(outer % inner == 0){
return true;
}
else{
return false;
}
}

The arguments are just swapped. You are calling the function as isAFactor(countOut, countIn) when you should be calling with isAFactor(countIn, countOut)

To clarify #Aki Suihkonen's comment, when performing:
outer % inner
If inner is zero, you will get a divide by zero error.
This can be traced backward by calling isAFactor(0, 1).
It is in your for loop in main.
The first parameter to isAFactor(countOut, countIn) is assigned in the outermost for loop:
for (countOut = 0; ...
Notice the value you are initializing countOut with.
Edit 1:
Change your `isAFactor` function to:
if (inner == 0)
{
cerr << "Divide by zero.\n";
cerr.flush();
return 0;
}
if (outer % inner ...
Place a breakpoint at either cerr line above.
When the execution stops there, look at the Stack Trace. A good debugger will also allow you to examine the parameter / values at each point in the trace.

Related

Why isn't break good enough?

C++
When I first ran this code with a different input value of 881, 643, 743, etc... which are all primes numbers, I got a result of "True" but when I input a higher number like 804047277, it came back as "True" when it should have been "False"
#include <iostream>
int main(){
int num;
std::cin >> num;
for(int i = 2; i < num; i++){
if(num % i == 0){
std::cout << "True" << std::endl;
break;
}
else{
std::cout << "False" << std::endl;
break;
}
}
return 0;
}
I corrected my code (The code below) and received the correct answer, which was "False"
#include <iostream>
int main(){
int num;
std::cin >> num;
for(int i = 2; i < num; i++){
if(num % i == 0){
std::cout << "True" << std::endl;
break;
return 0;
}
else{
std::cout << "False" << std::endl;
break;
}
}
return 0;
}
Shouldn't the break in the if statement stop the loop overall? I am just trying to understand why the break wasn't good enough, and I had to return 0;
I would correct your code like following (see description afterwards):
Try it online!
#include <iostream>
int main() {
int num = 0;
std::cin >> num;
for (int i = 2; i < num; ++i)
if (num % i == 0) {
std::cout << "True (Composite)" << std::endl;
return 0;
}
std::cout << "False (Prime)" << std::endl;
return 0;
}
Input:
804047277
Output:
True (Composite)
As it is easy to understand, your program is intended to check primality and compositness of a number.
Mistake in your program is that you show False (Prime) when division by a very first i gives non-zero remainder. Instead, to actually check primality, you need to divide by all possible i and only if ALL of them give non-zero, then number is prime. It means that you shouldn't break or show False on very first non-zero remainder.
If ANY of i gives zero remainder then given number by definition is composite. So unlike the Prime case, this Composite case should break (or return) on very first occurance of zero remainder.
In code above on very first zero remainder I finish program showing to console that number is composite (True).
And only if whole loop finishes (all possible divisors are tested) then I show False (that number is prime).
Regarding question if break; is enough to finish a loop, then Yes, after break loop finishes and you don't need to return 0; after break, this return statement never finishes.
Also it is well known fact that it is enough to check divisibility until divisor equal to Sqrt(num), which will be much faster. So your loop for (int i = 2; i < num; ++i) should become for (int i = 2; i * i <= num; ++i) which is square times faster.

A member test using Recursion

I was having trouble understanding recursion. I'm looking for some feedback here to see how this program looks.
Question :::
Write a recursive Boolean function named isMember. The function should accept three parameters: an array of integers, an integer indicating the number of elements in the array, and an integer value to be searched for. The function should return true if the value is found in the array or false if the value is not found. Demonstrate the use of the function in a program that asks the user to enter an array of numbers and a value to be searched for.
What I have::
#include <iostream>
using namespace std;
bool isMember(int[],int,int);
int main()
{
const int SIZE = 10;
int numSearch;
int elementz[SIZE];
for(int i = 0; i < SIZE; i++)
{
cout << "Element " << i + 1 << "\t";
cin >> elementz[i];
}
cout << "Enter element to search\n";
cin >> numSearch;
bool value = isMember(elementz,SIZE,numSearch);
if(value ==1)
cout << "Element is found\n";
else
cout << "Element not found\n";
return 0;
}
bool isMember(int arr[], int sizze, int num)
{
if(arr[sizze] == num)
return true;
else
isMember(arr,sizze -1, num);
}
Your function doesn't return if the if clause is false. Also, keep in mind that indexes start at 0, not 1 (and why sizze?).
I would recommend starting with an array of 3 values, rather than of 10. That way you''ll be able to manually follow and unfold the successive calls.
In order for recursions to work, you need not only a "conditional stop", but an inconditional stop too.
In your example, you only provided a conditional stop. To make it work correctly, try something like this:
bool isMember(int arr[], int sizze, int num)
{
if ( sizze < 0 ) // "inconditional stop"
return false;
if(arr[sizze] == num) // conditional stop. It could happen or not
return true;
else
isMember(arr,sizze -1, num);
}

C++ cout won't work inside for and if?

I have those two pieces of code as my home assignment. The code looks all fine to me, but it won't print out what I want, no matter what. In fact, the console output remains completely empty.
The first program is supposed to print out all numbers that fulfil the ladna() function requirements and are between 1 and a:
#include <iostream>
using namespace std;
int a;
int i = 1;
bool ladna(int a)
{
if((((a>>4)*5+a*2)%3)==1)
return true;
else
return false;
}
int main()
{
cerr << "Podaj liczbe: " << endl;
cin >> a;
while (i <= a){
if (ladna(a)){
cout << i << " ";
}
i++;
}
}
the ladna() function is premade and I have to use it as is.
I tried changing while into do...while and for, didn't help. Doesn;t work with cerr either.
The second code has to print out all the natural divisors of number a.
#include <iostream>
using namespace std;
int main()
{
int a;
cerr << "Podaj liczbe" << endl;
cin >> a;
for (int i = 0; i >= a; i++){
if (a % i == 0){
cout << i << endl;
}
}
return 0;
}
Doesn't work either.
To me it looks like both pieces of code have the same issue, because they are written in the same way, based on the same principle, and the error is the same. Hence my assumption, that the cause is the same as well.
Unfortunately, for the love of me, I simply can't see what said error is...
For the first code:
I think you should call ladna function with i, like ladna(i)
For the second code:
In for it should be i<=a
'%' is the modulo operator, during the execution of (a%i) you divide a with i and take the remainder, since i start with zero you will get "Floating point exception (core dumped)" due to division by zero. So, for should start with 1. This should work:
for (int i = 1; i <= a; i++){
if (a%i == 0){
cout << i << endl;
}
}

Need help to stop program terminating without users consent

The following code is supposed to do as follows:
create list specified by the user
ask user to input number
3.a) if number is on the list , display number * 2, go back to step 2
3.b) if number isn't on the list, terminate program
HOWEVER step 3.a) will also terminate the program, which is defeating the purpose of the while loop.
here is the code :
#include <iostream>
#include <array>
using namespace std;
int main()
{
cout << "First we will make a list" << endl;
array <int, 5>list;
int x, number;
bool isinlist = true;
cout << "Enter list of 5 numbers." << endl;
for (x = 0; x <= 4; x++)
{
cin >> list[x];
}
while (isinlist == true)
{
cout << "now enter a number on the list to double" << endl;
cin >> number;
for (x = 0; x <= 4; x++)
{
if (number == list[x])
{
cout << "The number is in the list. Double " << number << " is " << number * 2 << endl;
}
else
isinlist = false;
}
}
return 0;
}
Please can someone help me to resolve this ?
I would suggest that you encapsulate the functionality of step 3 into a separate function. You could define a function as follows, and then call it at an appropriate location in the main function.
void CheckVector(vector<int> yourlist)
{
.... // Take user input for number to search for
.... // The logic of searching for number.
if (number exists)
{
// cout twice the number
// return CheckVector(yourlist)
}
else
return;
}
The same functionality can be implemented with a goto statement, avoiding the need for a function. However, using goto is considered bad practice and I won't recommend it.
Your issue is that you set isinlist to false as soon as one single value in the list is not equal to the user input.
You should set isinlist to false ay the beginning of your while loop and change it to true if you find a match.
Stepping your code with a debugger should help you understand the issue. I encourage you to try it.

C++ Perfect Number With Nested Loops Issue

What I am trying to do is search for a perfect number.
A perfect number is a number that is the sum of all its divisors, such as 6 = 1+2+3.
Basically what I do here is ask for 2 numbers and find a perfect number between those two numbers. I have a function that tests for divisibility and 2 nested loops.
My issue is that I don't get any result. I've revised it & can't seem to find anything wrong. The compiler doesn't shoot out any errors.
What can be wrong?
#include <iostream>
using namespace std;
bool isAFactor(int, int);
int main()
{
int startval;
int endval;
int outer_loop;
int inner_loop;
int perfect_number = 0;
cout << "Enter Starting Number: ";
cin >> startval;
cout << "Enter Ending Number: ";
cin >> endval;
for(outer_loop = startval; outer_loop <= endval; outer_loop++)
{
for(inner_loop = 1; inner_loop <= outer_loop; inner_loop++)
{
if (isAFactor(outer_loop, inner_loop) == true)
{
inner_loop += perfect_number;
}
}
if (perfect_number == outer_loop)
{
cout << perfect_number << " is a perfect number." << endl;
}
else
{
cout << "There is no perfect number." << endl;
}
}
system("PAUSE");
return 0;
}
bool isAFactor(int outer, int inner)
{
if (outer % inner == 0)
{
return true;
}
else
{
return false;
}
inner_loop += perfect_number; should be perfect_number += inner_loop;.
There are other issues -- you need to reset perfect_number to zero in each outer loop, and you should presumably print the message "There is no perfect number." if none of the numbers in range is perfect, rather than printing it once for every number in range that is not perfect.
I'd advise that you rename perfect_number to sum_of_factors, outer_loop to candidate_perfect_number and inner_loop to candidate_factor, or similar.
after the if statement:
cout << perfect_number;
cout << outer_loop;
if (perfect_number == outer_loop)
{
cout << perfect_number << " is a perfect number." << endl;
}
and see what values they have
Updated:
What is the value of your endval? is 0?, and thats why the loop ends so early
Oh, so many issues.
The variable perfect_number never changes. Did your compiler flag
this?
The outer loop will be one more than the ending value when it exits;
did you know this?
You don't need to compare bool values to true or false.
You could simplify the isAFactor function to return (outer %
inner) == 0;.
You could replace the call to isAFactor with the expression
((outer % inner) == 0).