Error in while loop? - c++

I made a simple example for counting decimal points but it doesn't stop and doesn't give me the right answer here's my code:
double b=76327741.125;
int count=0;
while(b - (int)b > 0.0)
{
b*=10;
count++;
}
cout<<count;
the answer is supposed to be:
3
but instead the while loop keeps running Indefinitely .. what's wrong with my code?

You should have checked the INT_MAX first. The number would be different. It depends on whether you are running the code on a 32-bit or 64-bit machine. If it is way smaller than your initial b, you would definitely end up in the infinite loop. For example, the max of short integer type is 32767. In that case, the condition of your loop would be like this: 76327741.125 - some negative number, larger than 0. however, in the loop, you increased the value of b. The next time, when we hit the condition line, it would be something like this: 76327741.125*10 - some negative number

You should probably set b to be b - int(b), to make sure it doesn't keep increasing (and potentially overflowing).
double b=76327741.125;
int count=0;
while(b - (int)b > 0.0)
{
b = b - int(b); // Note the change here.
b*=10;
count++;
}
cout<<count;

Related

Why is the "if" not executed within a loop?

The cout << "Fin", it is never executed
int main(){
int num, suma=0, divisor=0;
cout<<"Escribe un número"<<endl;
cin>>num;
cout<<num<<": ";
while(divisor<num){
if(num % divisor==0){
cout<<divisor;
}
}
cout<<"Fin";
num % divisor with divisor=0 does division by zero, which typically leads to aborting.
You should give another initial value (maybe 1 or 2 looks good, depending on the purpose) to that.
Also, as #KfirVentura pointed out, you should update divisor (or num) in the loop, or the loop will run infinitely if divisor<num initially becomes true.
"if" loop would not run as divisor is 0 and for all conditions will give a runtime exception error, which is apparent. Try changing the value of divisor.

Program keeps spamming numbers?

#include <iostream>
using namespace std;
int main(){
int a;
int b;
int dif;
cout<<"insert a: "<<endl;
cin>>a;
cout<<"insert b: "<<endl;
cin>>b;
if(a>b){
while(dif>=3){
dif=a-b;
cout<<dif;
}
}else{
while(dif>=3){
dif=b-a;
cout<<dif;
}
}
}
This is supposed to be a program that reads two numbers and keeps subtracting the smaller one from the bigger one until the difference is < 3 units. While it does this it should also output the difference at every iteration and for some reason it spams the difference or doesnt output anything. Help?
Two problems in your while loops:
while(dif>=3){
dif=a-b;
cout<<dif;
}
First, dif is used uninitialized and using it will cause undefined behavior. After you fix that the loop will still not do what you want.
dif=a-b; will assign to dif the same value in every iteration, hence the loop will run either never (condition is false before the loop), once (condition is false after the assignment), or forever (condition is still true after the assignment). I suppose this isn't the intended behavior.
...and keeps subtracting the smaller one from the bigger one until the difference is < 3 units.
You forgot to actually subtract one number from the other. That would be (in case a is the bigger):
while ( a-b >= 3) a -= b;
or with an additional variable (I don't think it helps, but rather adds complexity):
int diff = a-b;
while (diff >= 3) {
a -= b;
diff = a-b;
}
You need to initialize dif to be a number, e.g. int dif = 0;. C++ doesn't say what happens when you manipulate or use an uninitialized variable, so anything can happen and your program won't work consistently- this is probably why you've had it produce no output. This phenomenon is known as undefined behavior- see here for a full explanation.
Additionally, your loops also go infinite- if a is greater than b, dif >=3, and you set dif = a - b, dif is always the same, so the condition will always be true, and thus your code never stops running. You need to subtract and reassign the variable first so the values change, and then update dif:
a = a - b
dif = a - b
The second loop has the same problem.
There are two issue here ..
diff is not assigned any default value so it gets random value, if it will be greater or equal than 3 it will print infinity and if it is less than it will do nothing.
initiaalize the diff with diff=abs(b-a)
if by chance diff enter the loop then on every iteration diff is not changing as a and b remain same. So change the logic.
Instead of if else and two while loops just use diff=abs(b-a)
Good Luck

Printing a value changes the output of the code

Few hours ago, a competition was held on CodeForces , this was one the questions of the competition -
Problem C (You dont have to read/solve it to answer the question)
EDIT : Adding the question here as requested, again, one does not necessarily have to read it.
Slastyona and her loyal dog Pushok are playing a meaningless game that
is indeed very interesting.
The game consists of multiple rounds. Its rules are very simple: in
each round, a natural number k is chosen. Then, the one who says (or
barks) it faster than the other wins the round. After that, the
winner's score is multiplied by k2, and the loser's score is
multiplied by k. In the beginning of the game, both Slastyona and
Pushok have scores equal to one.
Unfortunately, Slastyona had lost her notepad where the history of all
n games was recorded. She managed to recall the final results for each
games, though, but all of her memories of them are vague. Help
Slastyona verify their correctness, or, to put it another way, for
each given pair of scores determine whether it was possible for a game
to finish with such result or not.
Input In the first string, the number of games n (1 ≤ n ≤ 350000) is
given.
Each game is represented by a pair of scores a, b (1 ≤ a, b ≤ 10^9) –
the results of Slastyona and Pushok, correspondingly.
Output For each pair of scores, answer "Yes" if it's possible for a
game to finish with given score, and "No" otherwise.
You can output each letter in arbitrary case (upper or lower).
So I solved it, and after the competition was over, me and my friends were discussing the problems when they asked me what was my answer coming for the following test case -
1
1 1
I said it was "Yes" on my IDE (Dev-C++ 5.11), (as it was supposed to be)
But when we ran it on ideone, it came out to be "No" !!
I thought there must be a problem with my code only, so i tried debugging it when i came across this problem,
My Code -
#include<stdio.h>
using namespace std;
long long int iscube(long long int n)
{
long long int lo = 0;
long long int hi = 1000000;
while(lo < hi)
{
long long int mid = (lo+hi)/2;
if(mid*mid*mid < n)
lo = mid+1;
else
hi = mid;
}
return lo;
}
int main()
{
long long int a,b;
int n;
scanf("%d",&n);
while(n--)
{
scanf("%I64d %I64d",&a,&b);
long long int c = a*b;
long long int cb = iscube(c);
//printf("%lld",cb)
if(cb*cb*cb == c)
{
if(a%cb == 0 && b%cb == 0)
printf("Yes\n");
else
printf("No\n");
continue;
}
printf("No\n");
}
}
When i give the input as
1
1 1
in the above code, the answer comes out to be "No"
BUT if I ONLY uncomment the line above the if statement in the while loop in the main() function,
the answer would be "1 Yes"
(these outputs are the outputs i got when i ran the code on ideone, when running on Dev-C++ 5.11 , i got "Yes" and "1 Yes" as expected)
Now while i was thinking that my my answer of codeforces would be evaluated as WA, After the system test, it came out to be Accepted!
Does anyone have any idea on why this issue is arising?
(Also, could someone add the appropriate tags, if any)
Turn up your warnings, you have undefined behavior in your scanf:
warning: length modifier 'I64' results in undefined behavior or no effect with 'd' conversion specifier [-Wformat]
scanf("%I64d %I64d",&a,&b);
If you change it to scanf("%lld %lld",&a,&b); (C++11), then you'll have defined behavior, however since you're using C++, just use a stream instead:
std::cin >> a >> b;
Demo

Inifinite loop makes variable come out as 0

I have this piece of code in my school book.
#include<iostream>
using namespace std;
int main() {
int x=10,c=1;
while (c < 5) {
x += x*c;
c *= 2;
c++;
c -= 2;
cout << "X=" << x<<'\n';
}
system("pause");
return 0;
}
As you can see it's an infinite loop, when logically traced, it should show 20,40,80 and so on.
However it always shows 0.
when adding system("pause") after each loop cycle it shows the correct values, but when left as shown above (infinitely looping) it shows zero.
Any ideas of the reason?
c is always 1 no matter what. The loop becomes infinite. Eventually, X becomes 0 due to integer overflow.
c = 1
c *= 2; c = 2
c++; c = 3
c -= 2; c = 1 <-- infinite
Here is my answer for your questions:
Why do you get infinitely looping?
awesomeyi did answer you above, because the condition of the while loop is always true, so it is never ended.
Why does X always equal to 0?
Please pay your attention on X varable, its value will be increased after ending one loop x += x*c. Because you are in the infinitely loop, x's value will be increased forever until greater than the limited value of an integer variable. Then, the value will be set as zero. Please see my output when running your code.
Removing the pause doesn't cause it to always show zero. It just prints output so quickly that zeroes are all you see at the bottom. Add the pause back in and click through about 30-40 iterations and see if it helps you understand what is happening.

Floating Point Exception C++ Why and what is it?

I'm building a program for the Euler projects question 3, and while that might not really matter as a result I'm current trying to make this code take a number and test if it is prime or not. Now then before I get to troubleshoot the function it gives me the error "floating point exception" right after inputting the number. Here's the code:
int main()
{
int input;
cout << "Enter number: " << endl;
cin>> input;
int i = input/2;
int c;
for (i>0; i--;) {
c= input%i;
if (c==0 || i == 1)
cout << "not prime" << endl;
else
cout << "prime" << endl;
}
return 0;
}
so essentially why is it giving me a floating point exception and what does that even mean?
A "floating point number" is how computers usually represent numbers that are not integers -- basically, a number with a decimal point. In C++ you declare them with float instead of int. A floating point exception is an error that occurs when you try to do something impossible with a floating point number, such as divide by zero.
for (i>0; i--;)
is probably wrong and should be
for (; i>0; i--)
instead. Note where I put the semicolons. The condition goes in the middle, not at the start.
Lots of reasons for a floating point exception. Looking at your code your for loop seems to be a bit "incorrect". Looks like a possible division by zero.
for (i>0; i--;){
c= input%i;
Thats division by zero at some point since you are decrementing i.
Since this page is the number 1 result for the google search "c++ floating point exception", I want to add another thing that can cause such a problem: use of undefined variables.
Problem is in the for loop in the code snippet:
for (i > 0; i--;)
Here, your intention seems to be entering the loop if (i > 0) and
decrement the value of i by one after the completion of for loop.
Does it work like that? lets see.
Look at the for() loop syntax:
**for ( initialization; condition check; increment/decrement ) {
statements;
}**
Initialization gets executed only once in the beginning of the loop.
Pay close attention to ";" in your code snippet and map it with for loop syntax.
Initialization : i > 0 : Gets executed only once. Doesn't have any impact in your code.
Condition check : i -- : post decrement.
Here, i is used for condition check and then it is decremented.
Decremented value will be used in statements within for loop.
This condition check is working as increment/decrement too in your code.
Lets stop here and see floating point exception.
what is it? One easy example is Divide by 0. Same is happening with your code.
When i reaches 1 in condition check, condition check validates to be true.
Because of post decrement i will be 0 when it enters for loop.
Modulo operation at line #9 results in divide by zero operation.
With this background you should be able to fix the problem in for loop.