0

I'm still only starting out in C++ and haven't dealt with much type casting yet. I was under the impression that the syntax is (type) (variables) however, this does not seem to work in this case.

float calcSphere (int radius)
{
    float sphereSA;

    sphereSA =  (4 * PI *  (radius*radius));

    return sphereSA;

}

PI is a symbolic constant declared using #define PI 3.14 at the top of the code, I attempted to fix this problem by using (float) (4 * PI * (radius*radius)) but this did not solve anything. Google seems to return pretty obscure results on the subject too. Any solutions?

4

2 に答える 2

1

推測ですが、(MSVS を使用して) double を float にキャストする初期化に関する警告が表示されますか? または、すべてが「4」の整数 b/c としてキャストされることになる b/c を台無しにしている可能性がありますか?

もしそうなら、問題はあなたが数値を入力するとそれが double だということです。しかし、あなたはそれを浮動小数点数として使用しています。それを解決するには、その数値をキャストする必要があります。例えば

sphereSA = ((float) 4 * (float) PI * radius * radius);

ただし、コンパイラに PI に関する型情報を提供する方がよいでしょう。例えば

namespace MyConstants {
    const float PI = 3.141;
}
sphereSA = ((float) 4 * MyConstants::PI * radius * radius);
于 2013-02-28T19:53:05.447 に答える
-4

C スタイルのキャストを使用しています。キャストの構文は C++ で変更されました。次のようなものを探します。

dynamic_cast<something*>( yourthing );
于 2013-02-28T19:47:33.430 に答える