Please help

I was creating an factorial program that's only accept numbers from 1 to 10
so i did write an if statement like this:
1
2
3
4
5
 if (num >= 1 || num <= 10)
	 {hhh = true;}
	 else
	 {cout << "";
	 hhh = false;}

but it didn't work !
why???
please help me.
the full code is here:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 #include <iostream>
#include <cmath>
using namespace std; 
int main()

{
	int fact=1;
		int num;
		bool hhh = false;
	 do{
	cout << "Please enter number from 1 to 10: " << endl;
	cin >> num;
	 if (num >= 1 || num <= 10)
	 {hhh = true;}
	 else
	 {cout << "";
	 hhh = false;}
	 }
	 while (!hhh);
	for (int i = 1; i <=num; i++)
				{fact = fact * i;}
		cout << "the factor is: " << fact << endl;
		system("pause");
}
Last edited on
if (num >= 1 || num <= 10)
Every number is >= 1 or <= 10. I think you want && instead of ||
I wrote this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

int main() {
  int fact = 1;
  int num;

  do {
    std::cout << "Please enter number from 1 to 10: " << std::endl;
    std::cin >> num;
  } while (num < 1 || num > 10);

  for (int i = 1; i <= num; ++i) {
    fact *= i;
  }

  std::cout << "the factor is: " << fact << std::endl;

  return 0;
}


It fails when enter a char or string value. It would be interesting fix it.
Last edited on
One way is to get the input first into a string and check if every character is a digit and if yes convert it to an int before doing the calculation.

Little demo:

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
60
61
62
#include <iostream>
#include <string>
#include <stdlib.h>

using namespace std;


bool IsValidInput(const string& input, int& num);

int main(void)
{
  string buffer;
  int fact = 1;
  int num = 0;

  cout << "Enter a number between 1 and 10 (-1 to quit): ";
  cin >> buffer;

  while (buffer != "-1")
  {
    if (IsValidInput(buffer, num))
    {
      for (int i = 1; i <= num; ++i) 
        fact *= i;

      cout << "The factor is: " << fact << endl;

    }
    else
    {
      cout << "Invalid input - number must be between 1 and 10\n ";
    }
    cout << "Enter a number between 1 and 10 (-1 to quit) (-1 to quit): ";
    cin >> buffer;
  }  

  system("pause");
}

// input must be an int and must be >= 1 && <= 10
// if input is correct input be will converted to an int and  will be stored in num, 
// otherwise num is unchanged
// returns true if input is correct otherwise false

bool IsValidInput(const string& input, int& num)
{
  if (input.size() > 2)
    return false;

  for (int i = 0; i < input.size(); i++)
    if (!(input[i] > '0' && input[i] <= '9'))
      return false;

  int tmp = atoi(input.c_str());

  if ( tmp > 1 && tmp <= 10)
  {
    num = tmp;
    return true;
  }
  return false;
}
Last edited on
Topic archived. No new replies allowed.