Is my pseudo code for changing time format correct? [duplicate]

拈花ヽ惹草 提交于 2019-12-11 14:55:29

问题


I need to create a pseudo code that will prompt for time in 24 hours format, convert it to 12-hour format and also whether it is AM or PM. It will have to repeat until sentinel time of 9999 is entered. Below is what I had come out with, is it correct?

  1. Prompt for time
  2. Get time
  3. Enter this loop:

    DOWHILE (time != 9999)
    

    IF (time < 0000 OR time > 2400 OR (time%100 >=60))

    Display 'Invalid time'
    

    ELSE

    IF (time >= 1200 AND time <= 2400 )

        format  = 'pm'
        hours = (time/100) - 12
        mins = time%100
        Display 'The new time is ', hours, '.', mins, format 
    

    ELSE format = 'am'

    IF (time/100 = 00 )
        hours = (time/100) + 12
        mins = time%100
        Display 'The time is ', hours, '.', mins, format 
    
    ELSE
    
        hours = time/100
        mins = time%100
        Display ' 'The time is ', hours, '.', mins, format 
    
    ENDIF
    

    ENDIF

    ENDIF

    ENDO


回答1:


In Perl:

#!/usr/bin/env perl
use strict;
use warnings;

sub time_12h_to_24h
{
    my($t12) = @_;
    my($hh,$mm,$ampm) = $t12 =~ m/^(\d\d?):(\d\d?)\s*([AP]M?)/i;
    $hh = ($hh % 12) + (($ampm =~ m/AM?/i) ? 0 : 12);
    return sprintf("%.2d:%.2d", $hh, $mm);
}

sub time_24h_to_12h
{
    my($t24) = @_;
    my($hh,$mm) = $t24 =~ m/^(\d\d?):(\d\d?)/;
    my($ampm) = ($hh <12) ? "am" : "pm";
    $hh %= 12;
    $hh += 12 if $hh == 0;
    return sprintf("%d:%.2d %s", $hh, $mm, $ampm);
}

while (<>)
{
    chomp;
    my($input, $entry) = split / - /;
    my $time_24h = time_12h_to_24h($input);
    my $time_12h = time_24h_to_12h($time_24h);
    print "$input - $time_24h : $time_12h - $entry\n";
    #printf "%8s - %5s : %8s - %s\n", $input, $time_24h, $time_12h, $entry;
}

Sample data:

12:00 AM - 0000
12:01 AM - 0001
12:59 AM - 0059
01:00 AM - 0100
11:00 AM - 1100
11:59 AM - 1159
12:00 PM - 1200
12:59 PM - 1259
01:00 PM - 1300
11:59 PM - 2359
12:00 AM - 2400

Sample output:

12:00 AM - 00:00 : 12:00 am - 0000
12:01 AM - 00:01 : 12:01 am - 0001
12:59 AM - 00:59 : 12:59 am - 0059
01:00 AM - 01:00 : 1:00 am - 0100
11:00 AM - 11:00 : 11:00 am - 1100
11:59 AM - 11:59 : 11:59 am - 1159
12:00 PM - 12:00 : 12:00 pm - 1200
12:59 PM - 12:59 : 12:59 pm - 1259
01:00 PM - 13:00 : 1:00 pm - 1300
11:59 PM - 23:59 : 11:59 pm - 2359
12:00 AM - 00:00 : 12:00 am - 2400


来源:https://stackoverflow.com/questions/22550361/is-my-pseudo-code-for-changing-time-format-correct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!