小数点计数器
Decimal point counter?
我做了这个计数器,但它没有工作,我真的不知道如何修复它。计数器应该执行以下步骤:
a=1/1.5=0.66
a=0.66/1.49=0.44
a=0.44/1.48=0.29
所以最后的"a"应该是0.29但是小数点计数器不能正常工作,这是我的代码
#include <string>
#include <iostream>
using namespace std;
int main(){
string test="aaa";
double i,j;
double a=1.0;
for (size_t j = 0; j < test.size(); j++)
{
for ( i = 1.5;i > 0.0;i = i - 0.01)
{
while (test[j] == 'a')
{
a=a/i;
break;
}
}
}
cout <<"a="<<a<<endl;
system("pause");
return 0;
}
我如何修复小数点计数器,使其减少0.01与字符串中的每一个字符?
你的代码中有太多的循环。您可以只使用单个for
循环,并在循环中:
- 测试字符串中索引字符是否为
a
- 如果是,执行计算
这将导致如下内容:
#include <string>
#include <iostream>
int main(){
std::string test = "aaa";
double a=1.0;
for (std::size_t j = 0; j < test.size(); ++j) {
if (test[j] == 'a') {
a /= (1.5 - 0.01 * j);
std::cout << "a=" << a << 'n';
}
}
}
现场演示
进一步解释这一行:
a /= (1.5 - 0.01 * j);
你应该看到你的计算如下:
a = 1 / (1.5 - 0.01 * 0) = 0.66
a = 0.66 / (1.5 - 0.01 * 1) = 0.44
a = 0.44 / (1.5 - 0.01 * 2) = 0.30
:
a = 1 / (1.5 - 0) = 0.66
a = 0.66 / (1.5 - 0.01) = 0.44
a = 0.44 / (1.5 - 0.02) = 0.30
上面的代码将产生:
= 0.666667
= 0.447427
= 0.302316
我有点太慢了,但是这里有一个类似于Jeffrey给出的解决方案:
#include <string>
#include <iostream>
using namespace std;
int main(int, char**)
{
string test="aaa";
double i = 1.5;
double a = 1.0;
for (unsigned int j = 0; j < test.length(); ++j)
{
a = a / i;
i -= 0.01;
}
cout << "a=" << a << endl;
return 0;
}
结果类似于0.302316
相关文章:
- 循环在计数器中不起作用
- 用c++把小数点转换成八进制
- python集合的C++等价物是什么.计数器
- Python 集合.计数器,如何避免重复查找
- 请解释字谜的代码,我看不懂计数器数组,每个值已经是0
- 如何在 c++ 中将小数点后两位数的浮点数分配给另一个浮点数
- 使用 cin 时接受小数点后的 2 位数字
- std::shared_ptr 自定义参考计数器
- 英特尔 TBB 程序不会终止,可能会误用参考计数器
- 不正确的比较和交换计数器输出用于快速排序功能
- OpenSSL API,使用GCM(伽罗瓦计数器模式)进行AES加密
- C++ 在循环中添加计数器变量并再次初始化其值
- 使用 stod() 转换小数点后字母的字符串时没有例外
- 需要帮助才能在C++中创建类计数器
- 漂亮的计数器习语的错误或格式错误的静态订单惨败?
- 几乎总是自动和带计数器的循环
- 线程使用计数器C++
- 为什么使用 2 个嵌套循环 O(n^2) 复杂度来解决二和问题,当只改变循环计数器逻辑时运行得更快?
- 对于循环计数器不递增
- 小数点计数器