【问题标题】:Looping with different command line arguments from Ubuntu terminal从 Ubuntu 终端循环使用不同的命令行参数
【发布时间】:2018-06-22 09:03:56
【问题描述】:

我试图从 Ubuntu 终端 执行的 C 程序文件(在 Desktop 上)被命名为 distribution.c

我目前正在使用:

<admin-name>@<admin-name>-Latitude-E4310:~/Desktop$ g++ -o test distribution.c
<admin-name>@<admin-name>-Latitude-E4310:./test d0=0.3 d1=0.7 >output.txt

这适用于将 .c 程序文件生成的输出写入名为 output.txt 的 .txt 文件。但是,我的目标是为d0 的每个值生成输出文件,范围从0.01.0(以0.01 为步长)。一个约束是d1=1-d0。输出文件应命名为ouputxyz.txt,其中xyz 对应于d0 值中的三位数字。 (例如:当d0=0.10 时,输出文件名为output010.txt)。是否可以从 Ubuntu 终端本身为此任务编写 循环? (我不想为此在原始程序中添加另一个循环。)

顺便说一句,如果您需要有关我正在尝试做什么的任何其他详细信息,或者您认为问题可以改进和/或更具体,请在 cmets 中告诉我。我很乐意详细说明。

【问题讨论】:

  • 没有理由使用 C 标签,因为 testprogram 的创建方式无关紧要。只需搜索“bash for loop”,您会发现许多简单易用的示例

标签: linux bash ubuntu gcc


【解决方案1】:

Bash 不支持浮点运算 - 所以你必须求助于 bc 之类的东西 - 如下例所示。

最简单的做法是将其放在 Bash 脚本中。 (您需要安装bc。)

for ((i=0; i<=100; i++))
do
    x=`echo "scale=2; $i/100" | bc`
    y=`echo "scale=2; 1-$x" | bc`
    d0=`printf %.2f $x`
    d1=`printf %.2f $y`
    filename=`printf output%03d.txt $i`
    ./test d0=$d0 d1=$d1 >$filename
done

【讨论】:

  • 如果要改成for ((i=0; i&lt;=100; i++)),应该如何改scale的值呢?基本上我需要d00.01 的步骤遍历从0.01.0 的所有值。
  • @Blue:您需要设置scale=2。我已经更新了我的答案。
【解决方案2】:

这与上面的情况类似,但一个补充是另一个参数p也从0.00变化到1.00,步长为0.01

for ((n=0; n<=100; n++))
do
x=`echo "scale=2; $n/100" | bc`
y=`echo "scale=2; 1-$x" | bc`
    for ((i=0; i<=100; i++))
    do
        z=`echo "scale=2; $i/100" | bc`
        d0=`printf %.2f $x`
        d1=`printf %.2f $y`
        p=`printf %.2f $z`
        filename=`printf output%03d.txt $n`
        ./test L=1000 n=100 d0=$d0 d1=$d1 p=$p >>$filename
    done
done

【讨论】:

    猜你喜欢
    • 2020-04-23
    • 2020-03-12
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 2021-02-17
    • 2016-12-12
    • 2016-10-09
    • 2017-01-09
    相关资源
    最近更新 更多