stof对对象返回0,对普通变量工作正常。

问题描述 投票:0回答:1

我有一个存储一些值的向量,还有一个带有一些方法的天气类。其中一个方法是使用 stof 将一个字符串转换为 float,并对这个新值进行计算并返回。我看到 stof 对我的一个不属于类的独立变量有效,但当我调用这个对里面传递的字符串做 stof 的方法,并在计算后返回那个 float 值时,它返回的是 0,谁能解释一下这是为什么?

Main.cpp:

cout << "Before converting: " << solar1 << '\n';
windlog2.solar.SetSolar(solar1);
cout << "After converting: " << windlog2.solar.GetSolar() << '\n';

Weather. cpp:

float Weather::convertSolar(string solar1){

    float newValue = 0;

    newValue = stof(solar1);

    newValue = ((newValue)*(1/6))/1000;

    solar = newValue;

    return solar;

}

在我的cout语句中,转换前的值和我使用的字符串一样,转换后的值都是0。

c++ class vector methods
1个回答
3
投票

(1/6)0 因为这是一个整数除法。因此一切都变成了零。

newValue = ((newValue) * (1.f / 6.f)) / 1000.f;

应该是可以的。

© www.soinside.com 2019 - 2024. All rights reserved.