6
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

秒で与えられた時間を 時:分:秒に直す

Last updated at Posted at 2015-06-19

とあるオンラインジャッジでやった問題。
秒単位で与えられる時間を、時・分・秒に切り分けるようなコードを書く。
たとえば、入力として3680を与えると、1:1:20を出力する。
この出力はもちろんh:m:sの形である。

私が書いたコード

# include <cstdio>
int main(){
	int in; //入力
	int h=0; //時
	int m=0; //分
	int s=0; //秒

	scanf("%d",&in);

	while(in>=3600){ //時を決定
	in -= 3600;
	h++;
	}

	while(in>=60){ //分を決定
	in -= 60;
	m++;
	}

	s = in; //余りが秒

	printf("%d:%d:%d\n",h,m,s);
}

入力inから、3600秒(=1時間)を引けるだけ引く。引いた回数だけhをインクリメント。
次にinから60秒(=1分)を引けるだけ引く。引いた回数だけmをインクリメント。
最後に、insに代入。

より良いコード

他の人の回答を見ていたらこんなのがあった。
(丸写しはまずいので一応自分なりに書き直した)

# include <cstdio>
int main(){
	int in;
	int h,m,s;
	scanf("%d",&in);

	h = in / 3600;
	in %= 3600;

	m = in / 60;
	in %= 60;

	s = in;

	printf("%d:%d:%d\n",h,m,s);
}

整数同士の割り算が整数を返すことをうまく利用している。
剰余代入演算子なんてすっかり忘れていた。

感想

この問題で割り算を使うのって、小中学生でも思いつくんでなかろうか。これを思いつけないあたり頭が固くなってるなあ。

6
9
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?