I'm new too c++ and I had to design a program that determines the first four triangular square numbers and the output is exactly how I want it to be, but it wont quit after its printed the first four. I can't figure out what it could be. I can't CTRL C because I will get points taken off. What is the issue here?
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
//Prints name line
cout<<"*********** BY: ********"<<endl;
//Initializing
const int HOW_MANY=4;
int num=1;
int tsn=0;
int z=1;
int x=0;
//How many TSN it will find and be printed
while (x<=HOW_MANY)
{
//
int sum=0;
for (int y=0;y<512;y++)
{
sum+=y;
tsn=pow(num,2);
//Tests if the numbers are TSN
if ((sum==tsn) || (num+1)/sqrt(num)==sqrt(num))
{
//Prints 1-HOW_MANY TSN and what they are
cout<<"Square Triangular Number "<< z <<" is: "<< tsn <<endl;
z++;
x++;
}
}
num++;
}
return 0;
}
x
begins at 0
. Every time you find and print a number it gets incremented. You'll continue this, so long as x<=HOW_MANY
.
You say your program finds 4 numbers but keeps running. After 4 hits, x
will be 4. Is 4 <= 4
? The answer is yes, so your program keeps running.
Either change the condition to x < HOW_MANY
, or initialize x
to 1
.
Did a little leg work, it turns out the sum of all the numbers in the range [1,512] is 131328 . The 5th square triangle number is 1413721 .
This means after you find the fourth triangle number, you will never sum high enough to find the next one. This will result in the infinite loop you're seeing.
The answer above is still the correct fix, but this is the reason you end up with an infinite loop.
如果x = 0
则需要写while (x<HOW_MANY)
而不是while (x<=HOW_MANY)
while (x<HOW_MANY)
。
for
should be used for iteration and while
should be used for condition testing.
The problem, as has been noted, is that your x
condition variable is never being incremented to get you out of the outer loop. That's a logic error that can be avoided by using the appropriate control structure for the job.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.