如何打印选择 b 的系列之和

huangapple go评论80阅读模式
英文:

How to print the sum of the series of choice b

问题

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, 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");
        }
    }
}
英文:

I am new to this site I may have asked the question in the wrong manner, please forgive

I have completed the choice a but I can't get the desired result for the sum of choice b
I can print the series but can't print the sum 2 – 5 + 10 – 17 + 26 – 37 + …. Up to n terms

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

答案1

得分: 0

保持一个名为 sgn 的变量,在1和-1之间切换。在将每个项添加到总和之前,将其乘以 sgn,然后翻转 sgn 以准备处理下一个项:

int sgn = 1; 
for(f = 1; f <= n; f++)
{
    s = sgn * (f * f + 1);
    sum += s;
    sgn *= -1;
}
英文:

Keep a sgn variable that flips between 1 and -1.
Multiply each term by sgn before adding it to the sum, then flip sgn to get ready for the next term:

int sgn = 1; 
for(f=1;f&lt;=n;f++)
{
s=sgn*(f*f+1);
sum+=s;
sgn *= -1;
}

huangapple
  • 本文由 发表于 2020年10月18日 22:21:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/64414396.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定