A
A
Andrey2019-03-06 20:20:12
bash
Andrey, 2019-03-06 20:20:12

Did you translate from C++ to BASH correctly?

I rewrote the program from C ++ to BASH, but it does not work quite correctly, please help me find the error.

#include <iostream>
using namespace std;
 
int main() {
  int h1, m1, h2, m2, result = 0;
  cin >> h1 >> m1 >> h2 >> m2;
  while(true) {
    if(m1 == 0) {
      result += h1 > 12 ? h1 - 12 : h1 == 0 ? 12 : h1;
    } else if(m1 == 30) {
      result++;
    }
    if(h1 == h2 && m1 == m2) {
      break;
    }
    m1++;
    if(m1 == 60) {
      m1 = 0;
      h1++;
    }
  }
  cout << result << endl;
  return 0;
}

#!/bin/bash
res=0
read h1 m1 h2 m2
while [ 1 ]
do
  if (($m1==0))
  then
    if (($h1>12))
        then
            res=$(($res+$h1-12))
        else
            if (($h1==0))
            then
            	res=$(($res+12))
            else
            	$res=$(($res+$h1))
            fi
        fi
  else
    if (($m1==30))
    then
      res=$(($res+1))
    fi
  fi
 
  if (($h1==$h2 && $m1==$m2))
  then
    break
  fi
  m1=$(($m1+1))
 
  if (($m1==60))
  then
    m1=0
    h1=$(($h1+1))
  fi
done
echo $res

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jcmvbkbc, 2019-03-07
@jcmvbkbc

$res=$(($res+$h1))

extra $ at the beginning.

3
3vi1_0n3, 2019-04-27
@3vi1_0n3

It is possible somehow to avoid numerous if

#!/bin/bash
res=0
read h1 m1 h2 m2
while :
do
  if [ $m1 -eq 0 ]; then
    if [ $h1 -gt 12 ]; then
        dif=$(($h1-12))
    else
        [ $h1 -eq 0 ] && dif=12 || dif=$h1
    fi
    res=$(($res+$dif))
  else
    [ $m1 -eq 30 ] && ((res++))
  fi
 
  [ $h1 -eq $h2 ] && [ $m1 -eq $m2 ] && break
  ((m1++))
  [ $m1 -eq 60 ] && m1=0 && ((h1++))
done
echo $res

Although I won’t lie, I didn’t understand what task you are solving on the pluses. Maybe even easier.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question