小数点计数器

Decimal point counter?

本文关键字:计数器 小数点      更新时间:2023-10-16

我做了这个计数器,但它没有工作,我真的不知道如何修复它。计数器应该执行以下步骤:

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循环,并在循环中:

  1. 测试字符串中索引字符是否为a
  2. 如果是,执行计算

这将导致如下内容:

#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