简体   繁体   English

如何将“ for”用于变量和不同的数字?

[英]How I can use the “for” with a variable and different numbers?

I want to create a for like this: 我想为这样创建一个:

for(int i=-0.8;i<2;i+n){
...
}

I do have the error: error: not a statement. 我确实有错误:错误:不是声明。

Whats my mistake? 我怎么了 Can I do it like this? 我可以这样吗?

Thanks for help. 感谢帮助。

-Regards -问候

ChrizZly ChrizZly

for(int i=-0.8;i<2;i+n){

Here, i+n is not valid. 在此, i+n无效。 You need to assign the new value to i , so it should be like this 您需要将新值分配给i ,所以应该像这样

for(int i=-0.8;i<2;i=i+n){

or 要么

for(int i=-0.8;i<2;i+=n){

You also need to modify the type of i to double , as int doesnt have decimals. 您还需要将i的类型修改为double ,因为int没有小数。

for(double i=-0.8;i<2;i+=n){
int i=-0.8;

0.8 is a double value. 0.8是双精度值。 Should not be assigned to int 不应分配给int

for(int i=0;i<2;i++)//to increment i by one
or 要么

for(int i=0;i<2;i+=n)//increment i by n

you can search for compound operators in java. 您可以在Java中搜索复合运算符。

If you want to use double in loop, for the stopping condition you can use 如果要使用双循环,可以使用停止条件

for(double i = 0.0 ; Double.compare(i, n) > 0 ; i+=n)

Double.compare(d1, d2)   // is more precise for comparing double/float values
  • returns the value 0 if d1 is numerically equal to d2 如果d1在数值上等于d2,则返回值0
  • a value less than 0 if d1 is numerically less than d2 如果d1在数值上小于d2,则该值小于0
  • a value greater than 0 if d1 is numerically greater than d2 如果d1在数值上大于d2,则该值大于0

You are assigning a double value to an int . 您正在将一个double值分配给int This is invalid. 这是无效的。 Use: 采用:

double i = -0.8

You are not modifying the counter variable ( i ) in the step section. 您没有在步骤部分中修改计数器变量( i )。 i+n is a mathematical operation, not an assignment. i+n是数学运算,而不是赋值。 Use: 采用:

i += n

The condition is OK 条件还可以

Final for loop: 最终for循环:

for (double i = -0.8; i < 2; i += n){
    //...
}

First problem: 第一个问题:

int i=-0.8 (Type mismatch: cannot convert from double to int)

Second problem: 第二个问题:

in order to have a correct for statement you have to use an assignment where you wrote i+n 为了获得正确的for语句,您必须在写i+n地方使用赋值

This is a possible compiling snippet of code 这是一个可能的代码片段

    double n=10.0;
    for(double i=-0.8; i<2.0 ;i=i+n){
        ....    
    }

make it int i = 0; 使其为整数i = 0; or double = -0.8; double = -0.8; int i = -0.8 will be error because 0.8 is not integer. int i = -0.8将是错误的,因为0.8不是整数。 it double. 它加倍。 I hope you will get this. 我希望你能得到这个。

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

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