我正在尝试在 C++ 中创建一个控制台应用程序,提示用户输入一个浮点数,然后获取该数字并分离出整数部分和小数部分。
示例输出为:-
请输入浮点数:
800.589
整数部分为 800,小数部分为 0.589
我的解决方案如下所示:
#include <iostream>
#include <cmath>
using namespace std;
void spliceAnyNumber (double anyNumber)
{
double integerPart = 1;
double fractionPart = 1;
double *pIntegerPart = &integerPart;
double *pFractionPart = &fractionPart;
fractionPart = fmod(anyNumber,1);
integerPart = anyNumber - fractionPart;
cout << "The integer part is " << *pIntegerPart << " and the fraction part is " << *pFractionPart << "\n";
cout << endl;
cout << "The address of *pIntegerPart is " << &integerPart << "\n";
cout << endl;
cout << "The address of *pFractionPart is " << &fractionPart << "\n";
cout << endl;
}
int main()
{
cout << "Please enter a floating point number: ";
double anyNumber = 0;
cin >> anyNumber;
cout << endl;
spliceAnyNumber(anyNumber);
system("Pause");
return 0;
}
我编写了程序,但我也被要求将指针传递给函数并操作取消引用的值。我试图在下面这样做,但我从编译器那里得到了一堆错误。
#include <iostream>
#include <cmath>
using namespace std;
void spliceAnyNumber (double *pAnyNumber)
{
double integerPart = 1;
double fractionPart = 1;
double *pIntegerPart = &integerPart;
double *pFractionPart = &fractionPart;
&fractionPart = fmod(&anyNumber,1);
&integerPart = &anyNumber - &fractionPart;
cout << "The integer part is " << *pIntegerPart << " and the fraction part is " << *pFractionPart << "\n"; *pFractionPart << "\n";
cout << endl;
cout << "The address of *pIntegerPart is " << &integerPart << "\n";
cout << endl;
cout << "The address of *pFractionPart is " << &fractionPart << "\n";
cout << endl;
}
int main()
{
cout << "Please enter a floating point number: ";
double *pAnyNumber = &anyNumber;
cin >> *pAnyNumber;
cout << endl;
spliceAnyNumber(*pAnyNumber);
system("Pause");
return 0;
}
添加指针我哪里出错了?版本 1 有效,但版本 2 无效。