有没有一种方法可以检查scala中foreach循环中的条件。这个例子是我要遍历一个整数数组并对正数做一些任意的数学运算。
val arr = Array(-1,2,3,0,-7,4) //The array
//What I want to do but doesn't work
arr.foreach{if(/*This condition is true*/)
{/*Do some math and print the answer*/}}
//Expected answer for division by six is 0.333333333 \n 0.5 \n 0.666666667
//Which is 2/6, 3/6 and 4/6 respectively as they appear in the array
Run Code Online (Sandbox Code Playgroud)
我知道如何使用普通的for循环和if语句来执行此操作,但是我想使用它,因为我想摆脱Java。
谢谢
'
#include <stdio.h>
#include <math.h>
int main(){
int i;
float num = 4.700;
for(i=1;i<5;i++){
printf("%0.3f\tx%d\t\t=%d\n",num,(int)pow(10,i),(int)(num*pow(10,i)));
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
' 此代码将以下内容打印到控制台: '
4.7000 x10 =46
4.7000 x100 =469
4.7000 x1000 =4699
4.7000 x10000 =46999
Run Code Online (Sandbox Code Playgroud)
' 这个结果与所有浮点值不一致
1.2000 打印出 ...120...1200 等等
1.8000 又是奇怪的
我在 Codeblocks 工作,我的问题是为什么有些浮点数会以这种方式做出反应?我缺少 C 或 mingw 编译器的一些基础知识吗?还是我的代码有问题?
感谢您的帮助,如果是重复问题,请见谅