In: Computer Science
Write a program that calculates the floor of a decimal number as defined here. Basically the Floor of any decimal number x, is the nearest whole number less than or
equal to x. ( Code Should Be In C++)
Requirements
1) You must implement a function to calculate the floor (you cannot use C++'s floor function). Name it floorAndError). It will have a return value and a single parameter
2) The program will ask the user to input a number (let's call this variable userInput) in main
3) The number will be passed to floorAndError by Reference and no other variables should be passed in
4) The function should change the userInput variable to the nearest whole number less than or equal to the original value of userInput that was inputted by the user. Therefore if the user inputted 4.3 into the variable userInput, after the function runs userInput will have the value 4.0. (note if the user enters -4.3 the floor is actually -5, think about how you might do this)
5) The function should return how much the value was changed by, i.e., the difference the new value of userInput and the old value of userInput. SO if the user inputted 4.3 the function will return a value equal to 4.0-4.3= -.3
6) The program should define the function prototype above main and the function definition after main
7) All the program input and output should occur in main
8) The function comments must have a pre condition and post condition both at the function prototype and the function definition
9) All the rest of the code should include comments too
CODE IN C++:
#include <iostream>
using namespace std;
//method to calculate power
int pow(int x, int y){
if(y==0)
return 1 ;
return x * pow(x,y-1);
}
float floatAndError(float num){
int number = (int)num;
int multiplier = pow(10,6);
number = number * multiplier;
number = number / multiplier;
if(number<0)
number = number - 1 ;
cout<<"The floor of your number
is:"<<number<<endl;
float change = num - number;
return change ;
}
int main()
{
//decalring variable
float number;
//taking input from the user
cout << "Enter a floating point number:";
cin >> number;
//displaying the result
cout<<"the relative change of number with its
floor:"<<floatAndError(number)<<endl;
return 0;
}
OUTPUT: