如何打印选择序列b

问题描述

我是这个网站的新手,我可能以错误的方式提出了这个问题,请原谅

我已经完成了选择a,但是选择b的总和却无法获得理想的结果 我可以打印系列,但不能打印总和2 – 5 + 10 – 17 + 26 – 37 +…。最多n个词

import java.util.*;
class menu
{
    public static void main(String args[])
    {
        String choice="";
        Scanner sc=new Scanner(system.in);
        System.out.println("Enter your choice 'a' or 'b'");
        choice=sc.nextLine();
        switch(choice)
        {
            case "a":
            int i,j;
            for ( i=1; i <=5; i++)
            {
                for (j=5; j >=i; j--)
                {
                    if ((i + j) % 2 == 0) {
                        System.out.print("1 ");
                    } 
                    else 
                    {
                        System.out.print("0 ");
                    }
                }
                System.out.println();
            }
            break;
            case "b":
            System.out.println("Enter 'n' th term"); 
            int sum=0,f,s,into,n;
            n=sc.nextInt();
            for(f=1;f<=n;f++)
            {
                s=(f*f+1);
                sum+=s;
                
                
            }
            System.out.print(sum);
            break;
            default:
            System.out.println("Wrong Choice");
        }
    }
}

解决方法

保持@EnableRetry @SpringBootApplication public class RetryableDbConnectionApplication { public static void main(String[] args) { SpringApplication.run(RetryableDbConnectionApplication.class,args); } } 变量在1到-1之间翻转。 将每一项乘以sgn,然后再将其加到总和,然后翻转sgn为下一项做好准备:

sgn
,

int sgn = 1; for(f=1;f<=n;f++) { s=sgn*(f*f+1); sum+=s; sgn *= -1; } 开头的词条,然后处理剩余的但最后一个词条,以便您可以在除最后一个词条之外的所有术语之后打印适当的符号(即2)。请注意,您还需要将每个带有正确符号的项添加到+/-

sum

示例运行:

System.out.println("Enter number of terms: ");
int sum = 0,f,n,term;
n = sc.nextInt();

// Start term with 2
term = 2;

// Process the remaining but the last term
for (f = 2; f <= n; f++) {
    System.out.print(term + (f % 2 == 0 ? " - " : " + "));
    sum += f % 2 == 0 ? term : -term;
    term = term + (2 * f - 1);
}

// Process the last term
System.out.println(term);
sum += f % 2 == 0 ? term : -term;

// Display sum
System.out.print(sum);