英文:
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="";
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");
}
}
}
答案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<=n;f++)
{
s=sgn*(f*f+1);
sum+=s;
sgn *= -1;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论