I need help with my homework

User writes 2 numbers. How much is the whole part of the number and how much is the decimal part of the number.

I am new to this, and i tried to write a program but i completely failed it. Please help! It also has to ask the user if he wants to restart the program after 2 numbers being entered.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int _tmain(int argc, _TCHAR* argv[])
{
	float ncs;
	long cd;
	float ncds;
    short i;

	i=1;
	for(;i<= 2;)
	{
		cout<<"Enter a decimal number"<<endl;
		cin>>ncs;
		cd=(long)ncs;
		ncds=ncs-cd;
	    cout<<setprecision(2)<<"For "<<i+1<<". the number that is "<<ncs<<" is ";
		cout<<"decimal part= "<<ncds<<", the whole part: ";
		cout<<cd<<endl;
		i=i+1;
	}
	system("pause");
	return 0;
}
 
Last edited on
The following code may be sufficient for your purposes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <iomanip>
#include <limits>

using namespace std;

int main()
{
	long double ncs;
	long cd;
	long double ncds;
	char again = 'Y';
	const int BUFFER_SIZE = 256;

	do
	{
		system("CLS");
		for(int i = 0; i < 2; i++)
		{
		cout << "Enter a decimal number: ";
		while(!(cin >> ncs))
		{
			cin.clear();
			cin.ignore(BUFFER_SIZE, '\n');
			cout << "Enter a decimal number: ";
		}
		cin.ignore(BUFFER_SIZE, '\n'); 

		cd = static_cast<long>(ncs);
		ncds = ncs - cd;
		cout << setprecision(numeric_limits<long double>::digits10) 
			<< "The number you entered is "<< ncs << endl;
		cout << "The whole part is " << cd << endl;
		cout << "decimal part is " << ncds << endl;
		}

		cout << "Would you like to play again? (Y/N): Y\b";
		if((again = toupper(cin.get())) == '\n')
			again = 'Y';
		else 
			cin.ignore(BUFFER_SIZE, '\n');	
	}
	while(again == 'Y');

	return EXIT_SUCCESS;
}


If your grader is a stickler about rounding errors when there are too many decimal places or handling overflow for numbers that are too large, you may need to elaborate to prevent a user from inputting such data.
Last edited on
Topic archived. No new replies allowed.