Hi I just started using C and I'm usually comfortable with java but I've run into a logical error.
int main()
{
int number;
cout << "Number: " << endl;
cin >> number;
while (number != 0 || number > 0) {
number/3;
cout << number << endl;
}
if (number = 0) {
cout << "True" << endl;
}
else {
cout << "False" << endl;
}
return 0;
}
I want to check if the number inputted is divisible by 3, but it just keeps printing the number on repeat instead of dividing? Why is number/3; not working? Thanks in advance
CodePudding user response:
Several issues:
This line:
if (number = 0) {
Is assigning 0 to number, not comparing with it. Then the entire expression is evaluated as false and the else clause will execute and print "False" no matter the input. If you want to compare, you use == operator.
But your main algorithm has an issue:
while (number != 0 || number > 0) {
number/3;
cout << number << endl;
}
First, number/3 doesn't do anything because you aren't assigning the result to anything. Better:
number = number / 3;
But it doesn't matter since all integer division does is drop the remainder. So even if you make this fix, that loop will reduce any positive value of number to 0 anyway. If the user types 17, the algorithm will reduce number to the following:
number = 17 / 3; // prints 5
number = 5 / 2; // prints 2
number = 2 / 3; // prints 0
And then your code would still think 17 is divisible by 3.
And finally, if you just want to see if a number "is divisible by", use the modulo, %, operator. This computes the remainder of a division expression. Works with positive and negative numbers.
if (number % 3 == 0) {
printf("number is divisible by 3\n");
}
But I think the algorithm you are after is effectively this:
int result = number / 3;
if (result*3 == number) {
printf("number is divisible by 3\n");
}
CodePudding user response:
Do number = number / 3; and if (number == 0).
It should be same as Java
int main()
{
int number;
cout << "Number: " << endl;
cin >> number;
while (number != 0 || number > 0) {
number = number/3;
cout << number << endl;
}
if (number == 0) {
cout << "True" << endl;
}
else {
cout << "False" << endl;
}
return 0;
}
CodePudding user response:
change number/3; to number = number/3;
CodePudding user response:
You need to assign number/3 to a variable in order to change it's value. This can simply be done by stating:
number = number/3;
or in some languages:
number /= 3;
