In: Computer Science
Write a function posnum that prompts the user to enter a positive number and loops to error-check. It returns the square root of the positive number entered by the user. It calls a subfunction in the loop to print an error message. The subfunction has a persistent variable to count the number of times an error has occurred.
Here is an example of calling the function:
>> squarerootvalue = posnum
Enter a positive number: -5
Error #1: Follow instructions!
Does -5.00 look like a positive number to you?
Enter a positive number: -33
Error #2: Follow instructions!
Does -33.00 look like a positive number to you?
Enter a positive number: 4
squarerootvalue = 2
i used c++ langauge.Here is the following code:
============================================
#include <iostream>
#include <cmath> // included to use the sqrt function
using namespace std;
//defining the two functions for finding square root and
printing message
void posnum();
void printError(int x);
//persistant variable used to print the error number
static int errorNum=0;
//main function
int main() {
posnum();
}
//definition of functions
void posnum()
{
int num,Squarerootvalue;
cout<<"\nEnter a positive number: ";
cin>>num;
if(num>0)
{
Squarerootvalue=sqrt(num);
cout<<"Squarerootvalue ="
<<Squarerootvalue<<endl;
}
else
{
printError(num);
posnum();
}
}
void printError(int x)
{
errorNum++;
cout<<"Error #"<<errorNum<<": Follow
instructions!"<<endl;
cout<<"Does "<<x<<" look like a positive number
to you?";
}
please do upvote and comment for doubts.
Looking forward to help you :-)