Here's a C++ program that defines a function called splitFloat() that takes a floating-point number as an argument and returns its integer and fractional parts through reference arguments:
#include <iostream>
using namespace std;
void splitFloat(float num, int& intPart, float& fracPart) {
intPart = static_cast<int>(num);
fracPart = num - intPart;
}
int main() {
float num;
int intPart;
float fracPart;
cout << "Enter a floating-point number: ";
cin >> num;
splitFloat(num, intPart, fracPart);
cout << "Integer part = " << intPart << std::endl;
cout << "Fractional part = " << fracPart << std::endl;
return 0;
}
Output:
Enter a floating-point number: 3.14159
Integer part = 3
Fractional part = 0.14159
Explanation:
- The program defines a function called splitFloat() that takes a floating-point number num as an argument, and two reference arguments intPart and fracPart.
- The function first converts the floating-point number to an integer using a cast and stores the result in the intPart variable.
- It then calculates the fractional part of the number by subtracting the integer part from the original number, and stores the result in the fracPart variable.
- In the main() function, the program prompts the user to enter a floating-point number using cin.
- It then calls the splitFloat() function with the number and the integer and fractional part variables as arguments. The function updates the variables with their respective values.
- Finally, the program prints the integer and fractional parts to the console using cout.
No comments:
Post a Comment
If you have any doubts, please let me know