Formatting decimal numbers and outputting invalid messages.

I am having trouble with this code. I am supposed to make it to where if there is a number inputted for TV_Type that is not between 0 and 100 the program will display an invalid message and closes the program. Also, I am supposed to align the decimal places in the output screen. Any help would be greatly appreciated.

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
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <iostream>
#include <iomanip>
#include <math.h>

using namespace std;

int main()
{
	
// Initialize Variables

 int 	TV_Type=0;
 double TV_Size=0, LCD_Length=0, LCD_Width=0, LCD_Area=0,
 		Traditional_Length=0, Traditional_Width=0, Traditional_Area=0;
 
 // Prompt user for keyboard inputs
 
 cout << "Enter TV type (1-LCD, 2-Traditional): ";
 cin >> TV_Type;
 cout << "Enter TV size in inches: ";
 cin >> TV_Size;

// Calculate TV length

	LCD_Length = pow ((16.0/25.0) * TV_Size , 0.5);
	
	Traditional_Length = pow ((4.0/7.0) * TV_Size , 0.5);
	
// Calculate TV width

	LCD_Width = (9.0/16.0) * LCD_Length;
	
	Traditional_Width = (3.0/4.0) * Traditional_Length;
	
// Calculate TV area

	LCD_Area = LCD_Length * LCD_Width;
	
	Traditional_Area = Traditional_Length * Traditional_Width;
	
// Switch outputs

 switch (TV_Type)
{
 case 1:  cout << "TV Type: LCD" << endl;
           cout << "Length: " << setprecision(1) << fixed << LCD_Length << endl;
           cout << "Width: " << setprecision(1) << fixed << LCD_Width << endl;
           cout << "Area: " << setprecision(1) << fixed << LCD_Area << endl;
           break;
 case 2:  cout << "TV Type: Traditional" << endl;
           cout << "Length: " << setprecision(1) << fixed << Traditional_Length << endl;
           cout << "Width: " << setprecision(1) << fixed << Traditional_Width << endl;
           cout << "Area: " << setprecision(1) << fixed << Traditional_Area << endl;
           break;
 default:  cout << "You have entered an invalid TV type.";
}

return 0;
}
Try something like this:

1
2
3
4
5
6
7
8
9
10
11
12
 

int tv_type = 0;
cin >> tv_type;

if (tv_type >= 0 && tv_type <= 100){
   // your code
}
else{
   cout << "Invalid entry, exiting" << endl;
   exit(1)
}


you could use almost any other loop you are comfortable with to do this as well. Also, why do you need tv_type to be between 0 and 100 since there are only 2 types?
Last edited on
@talemache That was typo I meant TV_Size.Thank you anyways I will try this using TV_Size.
Topic archived. No new replies allowed.