Home > Software engineering >  the sum of 1 a a^2 _ _ _ a^n
the sum of 1 a a^2 _ _ _ a^n

Time:10-30

here is my code:

#include <iostream>
using namespace std;

int main()
{
    int s = 1, i, n, m;
    double a;
    cin >> a >> n;
    while (n <= 0)
    {
        cin >> n;
    }
    m = a;
    for (i = 1; i <= n; i  )
    {
        s  = m;
        m *= a;
    }
    cout << s << endl;
    return 0;
}

here was the start data: Given a real number a and a natural n, calculate the sum 1 a a^2 _ _ _ a^n, without using the formula for the sum of a geometric progression. The running time of the program must be proportional to n.

Input data Enter 2 numbers - a and n.

Output It is necessary to display the value of the sum. The checking program considers my code not full. Please explain where is the problem?

CodePudding user response:

Firstly, you don't need this while loop:

while (n <= 0)
{
    std::cin >> n;
}

What it does is keep input into n until you input a positive number, which probably isn't what you want.

Second, m *= a;. m is an int type, while a is a double type

#include <iostream>
// using namespace std; is bad, so don't use it

int main()
{
    // there's no need to declare a variable but leave it uninitialized.
    int a{};
    int n{};

    std::cin >> a >> n;

    unsigned long long m{a}; // this series grows very fast
                             //so it's best to store it in unsigned long long type
    unsigned long long s{1}  // same thing happen for s
    for (int i = 1; i <= n; i  ) // declare i in the loop scope
    {
        s  = m;
        m *= a;
    }                            // so now i is destroyed
    std::cout << s << '\n'; // use newline character instead of std::endl
    return 0;
}

CodePudding user response:

You are using an infinite loop to read the value of n.

#include <iostream>
using namespace std;

int main()
{
int s = 1, i, n, m;
double a;
cin >> a >> n;
// The below code was causing an endless loop
// while (n <= 0)
// {
//     cin >> n;
// }
m = a;
for (i = 1; i <= n; i  )
{
    s  = m;
    m *= a;
}
cout << s << endl;
return 0;
}

Commenting/removing the part of the code provides the result for the program.

  •  Tags:  
  • c
  • Related