The following is an assignment from my instructor. I have found a solution on Ch
ID: 3746891 • Letter: T
Question
The following is an assignment from my instructor. I have found a solution on Chegg that works, however let's say I enter 121(perfect square) it prints 120 when it should be printing 121 since it doesn't need to find the nearest perfect square since it is one. Any help is appreicated! I am programming in C...
Write a program that prompts the user for a positive integer and then reports the closest integer having a whole number square root. For example, if the user enters 8, then the program reports 9. If the user enters 18, then the program reports 16. The program should work for any number having one to seven digits.
Use the program template on Blackboard to include a meaningful program description(Ignore this part). Your program should check the user input to make sure it is positive. You may need to include <math.h> so that you can use functions floor() and ceil().
Explanation / Answer
// The header files of the program
#include<stdio.h>
#include<math.h>
//Main function
void main()
{
//Declare and initialize the variables
int input=0,upper=0,lower=0,diff=0,upper_square=0,lower_square=0;
int diff_upper=0,diff_lower=0;
float square_root=0;
//Get the input from user
printf(" Enter the number ");
scanf("%d",&input);
//Calculate the square root
square_root=sqrt(input);
//Calculate the upper limit
upper=ceil(square_root);
//Calculate the lower limit
lower=floor(square_root);
//Square the upper limit and lower limit
upper_square=upper*upper;
lower_square=lower*lower;
//Calculate the difference of upper limit and lower limit with the input
diff_upper=(upper_square)-(input);
diff_lower=(input)-(lower_square);
//Check if the entered number is perfect square
//If the upper limit and lower limit are same
if(upper==lower)
{
printf(" The entered number is perfect square %d",input);
}
//If not then check whether square of upper limit or the square
//of lower limit is near to the entered number
else if(diff_upper<diff_lower)
{
printf(" The nearest perfect square is %d",upper_square);
}
else
{
printf(" The nearest perfect square is %d",lower_square);
}
//End the program
getch();
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.