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

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

How to print the sum of the series of choice b

问题

  1. import java.util.*;
  2. class menu {
  3. public static void main(String args[]) {
  4. String choice = "";
  5. Scanner sc = new Scanner(System.in);
  6. System.out.println("Enter your choice 'a' or 'b'");
  7. choice = sc.nextLine();
  8. switch (choice) {
  9. case "a":
  10. int i, j;
  11. for (i = 1; i <= 5; i++) {
  12. for (j = 5; j >= i; j--) {
  13. if ((i + j) % 2 == 0) {
  14. System.out.print("1 ");
  15. } else {
  16. System.out.print("0 ");
  17. }
  18. }
  19. System.out.println();
  20. }
  21. break;
  22. case "b":
  23. System.out.println("Enter 'n' th term");
  24. int sum = 0, f, s, n;
  25. n = sc.nextInt();
  26. for (f = 1; f <= n; f++) {
  27. s = (f * f + 1);
  28. sum += s;
  29. }
  30. System.out.print(sum);
  31. break;
  32. default:
  33. System.out.println("Wrong Choice");
  34. }
  35. }
  36. }
英文:

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

  1. import java.util.*;
  2. class menu
  3. {
  4. public static void main(String args[])
  5. {
  6. String choice=&quot;&quot;;
  7. Scanner sc=new Scanner(System.in);
  8. System.out.println(&quot;Enter your choice &#39;a&#39; or &#39;b&#39;&quot;);
  9. choice=sc.nextLine();
  10. switch(choice)
  11. {
  12. case &quot;a&quot;:
  13. int i,j;
  14. for ( i=1; i &lt;=5; i++)
  15. {
  16. for (j=5; j &gt;=i; j--)
  17. {
  18. if ((i + j) % 2 == 0) {
  19. System.out.print(&quot;1 &quot;);
  20. }
  21. else
  22. {
  23. System.out.print(&quot;0 &quot;);
  24. }
  25. }
  26. System.out.println();
  27. }
  28. break;
  29. case &quot;b&quot;:
  30. System.out.println(&quot;Enter &#39;n&#39; th term&quot;);
  31. int sum=0,f,s,into,n;
  32. n=sc.nextInt();
  33. for(f=1;f&lt;=n;f++)
  34. {
  35. s=(f*f+1);
  36. sum+=s;
  37. }
  38. System.out.print(sum);
  39. break;
  40. default:
  41. System.out.println(&quot;Wrong Choice&quot;);
  42. }
  43. }
  44. }

答案1

得分: 0

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

  1. int sgn = 1;
  2. for(f = 1; f <= n; f++)
  3. {
  4. s = sgn * (f * f + 1);
  5. sum += s;
  6. sgn *= -1;
  7. }
英文:

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:

  1. int sgn = 1;
  2. for(f=1;f&lt;=n;f++)
  3. {
  4. s=sgn*(f*f+1);
  5. sum+=s;
  6. sgn *= -1;
  7. }

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:

确定