【问题标题】:How to cast a variable to degrees?如何将变量转换为度数?
【发布时间】:2013-10-10 13:35:04
【问题描述】:

我正在尝试通过将变量 tri2 包装在 toDegree() 中并将其设置为名为 triDegree 的新变量来将变量 tri2 转换为 degress。但是当我转换变量并运行应用程序时,我在 logcat 中得到以下信息:http://pastebin.com/HKDSAuQK

应用程序运行良好,并计算到我将其转换为度数的点。谁能在这里看到我的实施有什么问题?

public void onClick(View v) {
    // TODO Auto-generated method stub
    try {
        String getoffsetlength = data.offsetLength.getText().toString(); 
        String getoffsetdepth = data.offsetDepth.getText().toString(); 
        String getductdepth = data.ductDepth.getText().toString(); 

        double tri1,tri2;
        double marking1,marking2;
        double triDegree;

        double off1 = Double.parseDouble(getoffsetlength);//length
        double off2 = Double.parseDouble(getoffsetdepth);//depth
        double off3 = Double.parseDouble(getductdepth);//duct depth

        marking1 = Math.sqrt(Math.pow(off1,2) + Math.pow(off2,2));
        tri1 = Math.atan(off2 / off1);
        tri2 = (180 - tri1) / 2;
        triDegree = Math.toDegrees(tri2);
        marking2 = off3 / Math.tan(triDegree);

        Intent myIntent = new Intent(MainActivity.this, CalcResult.class);
        myIntent.putExtra("number1", marking1);
        myIntent.putExtra("number2", marking2);
        startActivity(myIntent);
        //make a toast 
        Toast.makeText( getBaseContext(), "Calculating!", Toast.LENGTH_SHORT
             ).show(); 
    }
    catch (NumberFormatException e) {
        // TODO: handle exception
        System.out.println("Must enter a numeric value!");
    }
}

【问题讨论】:

  • can't instantiate class com.example.offsetcalculator.MainActivity; no empty constructor 它说
  • 为什么评论说“//make a toast”?
  • @doctorlove This kind of toast,我猜

标签: java math casting 51degrees


【解决方案1】:

错误发生在这里:

tri2 = (180 - tri1) / 2;

此时,您在转换之前将tri1 视为度数。如果您想从“直”180° 角的值中减去一个角度,请使用 π 而不是 180,即 弧度 中直角的度量:

tri2 = (Math.PI - tri1) / 2;

这个调用也不正确

triDegree = Math.toDegrees(tri2);
marking2 = off3 / Math.tan(triDegree);

因为triDegree 以度数表示,而tan 期望以弧度表示的值。

【讨论】:

  • 所以我应该在 tri2 使用之前将 tri1 更改为度数。你能展示一个如何纠正这个问题的代码示例吗?
  • @BrianJ 要么,要么使用Math.PI,当角度以弧度测量时相当于180。
  • 我试过了,但它仍然崩溃。不确定代码中的问题是什么?
  • 所以我应该删除triDegree 并在marking 计算中使用原始的tri2 变量?但是如何将其转换为输出的度数?
  • @BrianJ 将数字保留为弧度,直到您准备好输出,然后调用 Math.toDegrees 以度数显示值。
猜你喜欢
  • 1970-01-01
  • 2011-08-23
  • 1970-01-01
  • 2016-02-10
  • 2011-08-12
  • 2017-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多