2

私は C++ が初めてで、コードの一部に苦労しています。ボタンのクリックで更新したいダイアログに静的テキストがあります。

double num = 4.7;
std::string str = (boost::lexical_cast<std::string>(num));
test.SetWindowTextA(str.c_str());
//test is the Static text variable

ただし、テキストは 4.70000000000002 として表示されます。4.7のように見せるにはどうすればよいですか。

.c_str()そうしないとcannot convert parameter 1 from 'std::string' to 'LPCTSTR'エラーがスローされるため、使用しました。

4

3 に答える 3

7

ここではの使用c_str()が正しいです。

書式設定をより細かく制御したい場合は、boost::lexical_cast自分で変換を使用および実装しないでください。

double num = 4.7;
std::ostringstream ss;
ss << std::setprecision(2) << num;  //the max. number of digits you want displayed
test.SetWindowTextA(ss.str().c_str());

または、ウィンドウ テキストとして設定する以上の文字列が必要な場合は、次のようにします。

double num = 4.7;
std::ostringstream ss;
ss << std::setprecision(2) << num;  //the max. number of digits you want displayed
std::string str = ss.str();
test.SetWindowTextA(str.c_str());
于 2013-10-02T11:39:35.040 に答える
2

なぜ物事をそれほど複雑にするのですか?char[]とを使用sprintfしてジョブを実行します。

double num = 4.7;
char str[5]; //Change the size to meet your requirement
sprintf(str, "%.1lf", num);
test.SetWindowTextA(str);
于 2013-10-02T12:17:56.403 に答える
1

double 型の 4.7 の正確な表現はありません。そのため、この結果が得られます。文字列に変換する前に、値を目的の小数点以下の桁数に丸めるのが最善です。

于 2013-10-02T11:40:30.553 に答える