简体   繁体   English

在Java中使用Scanner类打印X1-X3 + X5…n

[英]Using Scanner class in java to print X1-X3+X5…n

I was trying to print the following series: X 1 -X 3 +X 5 -X 7 .......X n 我正在尝试打印以下系列:X 1 -X 3 + X 5 -X 7 ....... X n

I have done everything but struck on changing the sign. 我已经做了所有事情,但是改变了标志。
Anybody has idea? 有人有主意吗?

Here is the code: 这是代码:

int n=10;int sum=0;int x=2;

double d=0.00;
for(int i=1;i<=n;i++){
    d = Math.pow(x,i);
    sum = sum + (int)d;
}

you should do some steps: 您应该执行一些步骤:

First way 第一种方式

  • use a boolean and name it as SIGN 使用boolean并将其命名为SIGN

    • change it's value each time you reach end of loop to determine sign based on 1 or 0 (true or false) 每次到达循环结束时都要更改其值,以基于1或0(正确或错误)确定符号
      • if sign was true use + 如果signtrue使用+
      • if sign was false use - 如果signfalse使用-
  • increase i in for loop twice ( i+=2 ) each time, so values of i will be 1, 3, 5, ... 增加i在for循环两次( i+=2 )各一次,所以值i将是1, 3, 5, ...


int n=10;int sum=0;int x=2;

double d=0.00;
boolean sign = true;
for(int i=1; i<=n ; i+=2 ){
    d=Math.pow(x,i);
    sum += ((sign)?(int)d:(-1*(int)d));
    sign = !sign;
}

Second way 第二种方式

  • use an integer and name it as SIGN 使用integer并将其命名为SIGN
    • change it's value each time you reach end of loop to determine sign based on 1 or -1. 每次到达循环结尾时,都要更改其值,以1或-1为基础确定符号。
  • since it has the same type as the iterator variable, you can define it in the loop. 由于它与迭代器变量具有相同的类型,因此可以在循环中定义它。

int n=10;int sum=0;int x=2;

for (int i = 1, sign = 1; i <= n; i += 2, sign = -sign) {
    sum += sign * (int)Math.pow(x, i);
}

you can input parameters by Scanner and change the sign by Math.pow(-1,n) . 您可以通过Scanner输入参数,并通过Math.pow(-1,n)更改符号。 code is as follows. 代码如下。

int sum = 0;
Scanner input = new Scanner(System.in);
System.out.println("please enter n:");
int n = input.nextInt();
System.out.println("please enter x:");
int x = input.nextInt();
for(int i = 1; i <= n; i += 2){
    sum += (int)Math.pow(-1, (i-1)/2) * Math.pow(x, i);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM