user9319233
user9319233

Reputation:

Creating a program to output 4 of the triangular square numbers

I'm creating a program to just output the first four triangular square numbers (1,36,1225,41616), but its only outputting "Square Triangular Number 1 is: 0". What am I doing wrong? Still new to C++.

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    for(int i=1;i<=4;i++);
    {
        int x=1;
        int test=0;
        test+=(1/32)*((pow((17+12*sqrt(2)),x))+(pow((17-12*sqrt(2)),x)-2));
        cout<<"Square Triangular Number 1 is: "<<test<<endl;
        x+=1;
    }

    return 0;
}

Upvotes: 1

Views: 328

Answers (2)

Arnav Borborah
Arnav Borborah

Reputation: 11789

  1. (1/32) does integer division.
  2. 1/32 is equal to 0.03125.
  3. 0.03125 gets truncated to 0 due to integer division discarding the fractional part of the number.
  4. test += 0 * <other_computations>.
  5. 0 multiplied by any other number is still 0.
  6. test = 0.

Also, your for loop does nothing 4 times in a row, just saying.

Upvotes: 4

FrankS101
FrankS101

Reputation: 2135

Two things are giving that output:

  1. for(int i=1;i<=4;i++);

The extra semicolon makes the for loop useless and your code inside the braces will be executed only once.

  1. test+=(1/32) * (the rest)

1/32 is an integer division which result is 0 * (the rest) is simply 0.

Upvotes: 1

Related Questions