Who can explain the steps to calculate this equation? Java

Write a program to calculate the following equation

I'm not asking for a solution Yes, it's a homework question, but I'm not here to copy and paste the answers I asked my professor to explain the problem or how should I deal with it? She said, "I can't tell you anything."

public static void main(String[] args){
    int i;

    for(i = 100; i >= 1; i--)
    {
        int result = i/j;
        j = j+1;
        System.out.println(result);
    }
}

Solution

When solving such problems, you can try to observe "trends" or "patterns"

Whereas: 100 / 1 99 / 2 98 / 3 97 / 4 96 / 5... 3 / 98 2 / 99 1 / 100

We get: numerator / denominator, let's call it divided by D (n / D)

Observed patterns:

> n – 1 after each cycle > d 1 after each cycle

So if you have 100 numbers, you need to cycle 100 times Therefore, it seems appropriate to use a for loop that loops 100 times:

for(int n=0; n<100; n++) //A loop which loops 100 times from 0 - 100

To start n with 100, we change the loop to start n with 100 instead of 0:

for(int n=100; n>0; n--) //A loop which loops 100 times from 100 - 0

You settled down n, now you need to start with 1

int d = 1; //declare outside the loop

Put everything together and you get:

int d = 1;
double result = 0.0;
for (int n=100; n>0; x--)
{
    result += (double)n/d; //Cast either n or d to double,to prevent loss of precision
    d ++; //add 1 to d after every loop
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>