In: Computer Science
for C++
I'm trying to write a code that asks for double values and counts how many times 2 consecutive values differ by at most 1. The output on 0 should be the answer.
With inputs 1, 1.7, 0.8, -0.1, -1, 0 : it should return 4 but keeps giving me 0. This is the correct output because only 1 and 1.7 differ by at most 1 as does 1.7 and 0.8, 0.8 and -0.1, and -0.1 and -1. We do not check whether 0 is within 1 of the previous number because 0 is the input that causes us to exit.
Why is this if every time a number differs by at least one my if statement should n++?
#include <iostream>
using namespace std;
int main ()
{
double n1, n2 = 0;
int n = 0;
cout << "Enter a number." << endl;
cin >> n1;
while (n1 != 0) {
if ((n1 - n2) > -1
&& (n1 - n2) < 1) {
n++;
n1 =
n2;
}
else {
cout
<< "Enter another number or 0 to end." << endl;
cin
>> n1;
}
}
cout << n << endl;
return 0;
}
Here is the corrected code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
#include <iostream>
using namespace std;
//method to return the absolute value of a number
//i.e. this method removes the sign of a number if it is negative
int abs(double n)
{
//if negative, returning negative of that number, which will be positive
if (n < 0) {
return -n;
}
//otherwise, returning that number
return n;
}
int main()
{
double n1, n2 = 0;
int n = 0;
cout << "Enter a number." << endl;
cin >> n1;
//looping as long as n1 is not 0
while (n1 != 0) {
//prompting and reading next number
cout << "Enter another number or 0 to end." << endl;
cin >> n2;
//checking if n2 is not 0
if (n2 != 0) {
//finding absolute value of n1-n2 and checking if it is under 1
//i.e subtracting n2 from n1 and removing the sign, so we dont have to check for
//both cases separately, and this value will be positive. if it is less than or
//equal to 1, then incrementing n
if (abs(n1 - n2) <= 1) {
n++;
}
}
//assigning n2 to n1
n1 = n2;
}
//displaying n
cout << n << endl;
return 0;
}
/*OUTPUT*/
Enter a number.
1
Enter another number or 0 to end.
1.7
Enter another number or 0 to end.
0.8
Enter another number or 0 to end.
-0.1
Enter another number or 0 to end.
-1
Enter another number or 0 to end.
0
4