简体   繁体   English

在C中使用多个循环

[英]Using Multiple For-Loops in C

My assignment is a coin-toss simulation that has to run 10, 100, 1000, 100,000 and 1 million trials. 我的任务是投币模拟,必须进行10、100、1000、100,000和1百万次试验。 In other words, one execution of the program encompasses all six trials. 换句话说,该程序的一次执行包含所有六个试验。 The code for the actual coin toss must be done in another function. 实际抛硬币的代码必须在另一个功能中完成。 I'm wondering whether it's possible to write a program that has multiple non-nested loops, such as: 我想知道是否可以编写具有多个非嵌套循环的程序,例如:

for(unsigned int counter = 1; counter <= 10; counter++)

for(unsigned int counter = 1; counter <= 100; counter++)

Etc 等等

EDIT: The output must say something like: 编辑:输出必须说类似:

Trials: 10   Heads: 30% Tails 70%
Trials: 100 ….

And so on. 等等。 Forgot to include this, sorry! 忘了包括这个,对不起!

Obviously, this is very tedious to write, and I don't want to have to call my coinToss function six times; 显然,这写起来很繁琐,而且我不想调用我的coinToss函数六次。 but I'm not sure how else to simulate the coin-toss under each trial (10... 1 million). 但是我不确定在每次试验(10 ... 1百万)下还能如何模拟投币游戏。

There are lots of ways to do this. 有很多方法可以做到这一点。 Here are a few. 这里有一些。

1) Use an outer loop to generate the number of trials. 1)使用外部循环生成试验次数。 Works well if the number of trials follows an easily generated pattern, which is the case in your question. 如果试验次数遵循易于生成的模式,则效果很好,在您的问题中就是这种情况。

for (unsigned int trials = 10; trials <= 1000000; trials *= 10)
    for(unsigned int counter = 1; counter <= trials; counter++)
    {
        // do stuff
    }

2) Use a table with arbitrary values if the pattern is not easy to generate. 2)如果不容易生成模式,请使用具有任意值的表。

unsigned int trials[] = { 15, 97, 1003, 10100, 100444, 999999, 0 };
for (int i = 0; trials[i] > 0; i++)
    for(unsigned int counter = 1; counter <= trials[i]; counter++)
    {
        // do stuff
    }

3) Put the loop into a function and call the function multiple times. 3)将循环放入函数中,并多次调用该函数。

void foo(unsigned int trials)
{
    for(unsigned int counter = 1; counter <= trials; counter++)
    {
        // do stuff
    }
}

int main(void)
{
    foo(10);
    foo(100);
    foo(1000);
    foo(10000);
    foo(100000);
    foo(1000000);   
}

You can also combine 3) with 1) or 2). 您也可以将3)与1)或2)结合在一起。 For example combining 3) with 1) looks like this 例如,将3)与1)结合起来看起来像这样

void foo(unsigned int trials)
{
    for(unsigned int counter = 1; counter <= trials; counter++)
    {
        // do stuff
    }
}

int main(void)
{
    for (unsigned int trials = 10; trials <= 1000000; trials *= 10)
        foo(trials);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM