我想将float值的符号作为int-1或1 的值.
避免条件总是降低计算成本的好主意.例如,我能想到的一种方法是使用快速bit-shift获取标志:
float a = ...;
int sign = a >> 31; //0 for pos, 1 for neg
sign = ~sign; //1 for pos, 0 for neg
sign = sign << 1; //2 for pos, 0 for neg
sign -= 1; //-1 for pos, 1 for neg -- perfect.
Run Code Online (Sandbox Code Playgroud)
或者更简洁:
int sign = (~(a >> 31) << 1) - 1;
Run Code Online (Sandbox Code Playgroud)
我最近开始学习Java。我的老师给了我们这份作业,内容是关于编写If-Else下面的Switch-Case语句代码并将其转换为语句代码。我If-Else正确编写了该语句代码,但其中Switch-Case一个似乎有一些错误。我越早得到答案越好。谢谢。
我要转换的内容:
int x;
System.out.println("type in a mark to see what grade it is");
Scanner input = new Scanner(System.in);
x = input.nextInt();
if (x >= 90 && x <= 100) {
System.out.println("A");
}
if (x >= 80 && x < 90) {
System.out.println("B");
}
if (x >= 70 && x < 80) {
System.out.println("C");
}
if (x >= 60 && x < 70) {
System.out.println("D");
}
if (x >= 50 && x …Run Code Online (Sandbox Code Playgroud)