I am attempting to fix a program for C++. I want to know two things. One: What t
ID: 3819353 • Letter: I
Question
I am attempting to fix a program for C++. I want to know two things. One: What type of exception is in the program below? (Example: logic_error, runtime_error, etc) and two: How would I add a try-block/catch-block to the program below in order to make it work correctly? If someone could explain this all to me, that'd be great. Thank you.
#include <iostream>
using namespace std;
int main()
{
double number, power;
cout<<" Enter a number: "; cin>>number;
for(long long k=1;; k+=100)
{
power = pow(number,k);
cout<<" Result: "<<number<<"^"<<k<<"="<<power<<endl;
}
cout<<endl;
system("pause");
return 0;
}
Explanation / Answer
It would have been more informative if you could have shared the exact issue that you are facing.
Anyway, I see following issue in the code.
1) The For loop goes into an infinite loop because no loop condition has been specified . You might be doing it intentionally but if you are not then you should do something like this :
for(long long k=1; k <= 1000 ; k+=100) // Any condition that breaks the loop after finite iterations
{
power = pow(number,k);
cout<<" Result: "<<number<<"^"<<k<<"="<<power<<endl;
}
Even if you are doing it intentionally, it has a problem. The power() function can accept only value within the range of double data type and can output the result within the range of double data type. Since you are increasing the value of "k" without bounds , the result may exceed the range of the double datatype.
DBL_MAX and DBL_MIN macros define the upper and lower limits of the double datatype and is defined in <cfloat> header file.
After reaching a maximum value the result will wrap aroung and start for DBL_MIN value which is a negative value.
Please comment if you need more info.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.