对于任何计数,for 循环运行一半
For loop runs half for any count
我正在尝试计算 运行 某个测试的成功结果的数量,该测试只有 2 个结果,成功或失败(下面未给出测试代码)。
我需要一个运行测试 20 次并打印出 20 次成功率的循环。
我不知道为什么,但我的循环只打印输出 10 次!情况总是如此。当我将结束条件更改为 20 以外的任何数字时,它只打印该数字一半的运行。
附件只是相关的代码片段。逻辑有问题吗?我找不到它。
double successRate = 0; //initialize variable recording total times of successes of test
for (int count = 1; count <= 20; count++)
{
string result = sf(fliptest()); //result of running the test the first time, only equals one of two strings: "success" or "failure"
if (result =="success")
{
successRate++;
cout << result << endl;
count++;
}
else
{
cout << result << endl;
count++;
}
}
cout << "The % of success is" << (successRate/20)*100 << " %" << endl;
删除 if 和 else 条件中的 count++。它会再次增加计数值,因此它会加倍,并且您将获得 20 次中一半的输出。
您正在递增 for 语句和 if else 块中的 count 变量,请从 for 循环或 if else 块中删除 count++。
这应该有效:
double successRate = 0; //initialize variable recording total times of successes of test
for (int count = 1; count <= 20; count++)
{
string result = sf(fliptest()); //result of running the test the first time, only equals one of two strings: "success" or "failure"
if (result =="success")
{
successRate++;
cout << result << endl;
}
else
{
cout << result << endl;
}
}
cout << "The % of success is" << (successRate/20)*100 << " %" << endl;
没有。你的 for 循环应该 运行 减少一半,因为你递增 "count" 两次,一次在 for 语句中,一次在 for 语句的主体中。删除两者之一即可解决问题。
我正在尝试计算 运行 某个测试的成功结果的数量,该测试只有 2 个结果,成功或失败(下面未给出测试代码)。 我需要一个运行测试 20 次并打印出 20 次成功率的循环。 我不知道为什么,但我的循环只打印输出 10 次!情况总是如此。当我将结束条件更改为 20 以外的任何数字时,它只打印该数字一半的运行。
附件只是相关的代码片段。逻辑有问题吗?我找不到它。
double successRate = 0; //initialize variable recording total times of successes of test
for (int count = 1; count <= 20; count++)
{
string result = sf(fliptest()); //result of running the test the first time, only equals one of two strings: "success" or "failure"
if (result =="success")
{
successRate++;
cout << result << endl;
count++;
}
else
{
cout << result << endl;
count++;
}
}
cout << "The % of success is" << (successRate/20)*100 << " %" << endl;
删除 if 和 else 条件中的 count++。它会再次增加计数值,因此它会加倍,并且您将获得 20 次中一半的输出。
您正在递增 for 语句和 if else 块中的 count 变量,请从 for 循环或 if else 块中删除 count++。
这应该有效:
double successRate = 0; //initialize variable recording total times of successes of test
for (int count = 1; count <= 20; count++)
{
string result = sf(fliptest()); //result of running the test the first time, only equals one of two strings: "success" or "failure"
if (result =="success")
{
successRate++;
cout << result << endl;
}
else
{
cout << result << endl;
}
}
cout << "The % of success is" << (successRate/20)*100 << " %" << endl;
没有。你的 for 循环应该 运行 减少一半,因为你递增 "count" 两次,一次在 for 语句中,一次在 for 语句的主体中。删除两者之一即可解决问题。