计算输出的尝试次数

时间:2016-11-06 01:59:18

标签: linux bash

这个问题是关于脚本的输出, 因为我需要知道我做了多少尝试......

typedef struct bst{
    int value; 
    struct bst* right; 
    struct bst* left; 
}BSTn;                //Binary Search Tree node

//Prototype: 
int height(BSTn* b);
void insert(BSTn** root, int value); 
void print(BSTn* b); 

void print(BSTn* b){
    BSTn** level_pointers =  (BSTn**)malloc( sizeof(BSTn*));
    level_pointers[0] = b;                 //Copy of the pointer to the root
    int level_pointers_len = 1;    //Initial length of the array of pointers
    int new_level_index;                                    
    int new_level_len;
    BSTn** new_level = (BSTn**) malloc(2*level_pointers_len* sizeof(BSTn*));  
    //Each new level is max twice the previous

    while(1){

        new_level_index = 0; 
        for (int i = 0; i < level_pointers_len; i++){
            printf("%i \t", level_pointers[i]->value);  
            if (level_pointers[i]->left != NULL){
                new_level[new_level_index] = level_pointers[i]->left; 
                new_level_index ++; 
            }
            if (level_pointers[i]->right != NULL){
                new_level[new_level_index] = level_pointers[i]->right; 
                new_level_index ++; 
            }

        printf("\n"); 
        }
        if (new_level_index == 0) 
            return; 
        new_level_len = new_level_index + 1; 
        level_pointers = (BSTn**)realloc(new_level, new_level_len*sizeof(BSTn*)); 
        new_level = (BSTn**) malloc(2*level_pointers_len* sizeof(BSTn*)); 
        level_pointers_len = new_level_len; 
    }   
}

,以下输出为:

输入猜谜编号:

23

打印更高的数字

输入猜谜编号:

34

打印更高的数字

输入猜谜编号:

45

打印更高的数字

输入猜谜编号:

47

这是一个正确的数字

如何编写代码以显示额外的一行,说明为达到正确答案所做的尝试次数?

1 个答案:

答案 0 :(得分:0)

你离这么远。

这将在bash递增一个名为$attempts的变量(从1开始),每次尝试错误答案时执行此操作。

循环消息使用$lastmsg变量使每次显示相关提示变得简单。

#!/bin/bash
guessno=47                                        # Set the number to guess
attempts=1                                        # Initial attempts is 1
while true;                                       # Run forever until exit
do
    clear
    echo "$lastmsg"                               # Display last message
    read -p "enter the guessing number" num
    if [[ $num -eq "$guessno" ]]; then
        echo "Correct"
        echo "It took "$attempts" attempt(s)"
        exit                                       # Exit program here
    fi
    if [[ $num -le "$guessno" ]]; then
        lastmsg="print higher number"              # Update $lastmsg
        (( attempts ++ ))
    elif [[ $num -ge "$guessno" ]]; then
        lastmsg="print lower number"               # Update $lastmsg
        (( attempts ++ ))
    fi   
done

请注意,整个程序都是在无限循环中进行的,并且正确的答案直接退出程序。