简体   繁体   English

浮动类型。 而且,

[英]float type with . and ,

I wrote this code: For each line, it should take the weighted average of these numbers with weights 0.2, 0.4, and 0.4, and it should print out the averaged value on a seperate line on the standard output. 我编写了这段代码:对于每一行,它应该采用权重为0.2,0.4和0.4的这些数字的加权平均值,并且应该在标准输出的单独行上打印出平均值。 For example, for the input below 例如,对于下面的输入

45.00 67.00 98.00
89.00 23.00 89.00

it should produce 它应该产生

75.00
62.60

It works when i write, for example 45,6 but it doesn't when i write 45.6. 它在我写的时候工作,例如45,6,但是当我写45.6时它没有。 This is my code: 这是我的代码:

import java.util.Scanner;

public class paket {
   public static void main (String [] args){
       Scanner input=new Scanner(System.in);
       float num1,num2,num3,result;

       while(input.hasNext()){

            num1=input.nextFloat();
            num2=input.nextFloat();
            num3=input.nextFloat();

            result= (float) (num1*0.2+num2*0.4+num3*0.4);

            System.out.println("Result is  " +result);
       }
   }
} 

在解析数字之前更改您的语言环境:

Locale.setDefault(new Locale("en", "US"));

A Scanner relies on a Locale to decide how to interpret its input. 扫描程序依赖于区域设置来决定如何解释其输入。 As other comments have noted, you're running on a system that assumes ',' is the decimal-point, rather than '.' 正如其他评论所指出的那样,你运​​行的系统假定','是小数点,而不是'。'

You can change the Locale your 'input' Scanner uses with 您可以更改扫描仪使用的“输入”区域设置

input.useLocale(Locale.US);

to have it interpret floats as using '.' 让它将浮动解释为使用'。' for the decimal point. 小数点。

You can set it back to your system's default with 您可以将其设置回系统的默认值

input.reset();

You should use the locale when parsing, this way you support both . 解析时应该使用语言环境,这样就可以同时支持。 and , depending on what the user have chosen: 并且,取决于用户选择的内容:

NumberFormat format = NumberFormat.getInstance(Locale.getDefault());      
Number number = format.parse("1,234");   
double d = number.doubleValue();

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

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