小编Jor*_*der的帖子

如何在Unix Shell中遍历字符串中的每个字母

我试图通过read命令迭代作为输入的字符串.我正在尝试输出每个字母和每个字母的数量然后应该使用循环依次输出每个字母.例如,如果用户输入"picasso",则输出应为:

信1:p信2:我信3:c信4:信5:信6:信7:o

这是我目前的代码:

#!/bin/bash

# Prompt a user to enter a word and output each letter in turn.


read -p "Please enter a word: " word

for i in $word
do
 echo "Letter $i: $word"
done
Run Code Online (Sandbox Code Playgroud)

我应该将输入放入数组吗?我仍然是编程循环的新手,但我发现无法弄清楚逻辑.

有什么建议?谢谢.

unix bash shell

4
推荐指数
3
解决办法
1万
查看次数

使用while循环来计算数字的平方根的近似值

我正在尝试使用包含while循环的函数来计算数字的平方根。在while循环的条件下,我想将两个值的比率的绝对值(即估计的平方根和数字)与1进行比较。但是,每当我运行程序时,我都会不断得到一个输出1.414214的无限循环。有什么帮助吗?谢谢。

// Function to calculate the absolute value of a number

#include <stdio.h>

float absoluteValue (float x)
{
    if ( x < 0 )
        x = -x;
    return (x);
}

// Function to compute the square root of a number

float   squareRoot (float x, const float epsilon)
{
    float       guess = 1.0;

    while ( absoluteValue ((guess * guess) / x) != epsilon ) {
        guess = ( (x / guess) + guess ) / 2.0;
        printf("%f\n", guess);
    } …
Run Code Online (Sandbox Code Playgroud)

c function while-loop square-root

2
推荐指数
1
解决办法
827
查看次数

标签 统计

bash ×1

c ×1

function ×1

shell ×1

square-root ×1

unix ×1

while-loop ×1