#1
by OverKuro » 4年前
この掲示板で初めて質問させていただきます。
もう少しきれいな書き方があれば教えていただけないでしょうか
やりたいこと:Startに設定した値から、Endに設定した値までStepの値ずつ繰り返し値を表示したい。
条件:
・StartとEndはかならず表示したい。
->Start = 5, End = 0, Step = 2の場合 : 5, 3, 1 ではなく 5, 3, 1, 0と表示したい
・実際にはdouble型の値を使うので、for文を使いたくない。
現在やりたいことは実質達成できているのですが、個人的に無理やり感があるため、もう少しきれいな書き方があるかどうかを模索している最中です。
コード:
#include <stdio.h>
#include <iostream>
using namespace std;
void main(){
//設定値
double start = 5;
double end = 0;
double step = 2;
//Startの値を代入
double count = start;
do
{
//countの値を表示
cout << count << endl;
//値がendと一致した場合ループを抜ける
if(count == end){
break;
}
//countをStepの値だけ減らす
count -= step;
//countの値がend未満の場合、countの値をendに変更してコンティニュー
if(count < end){
count = end;
continue;
}
} while (count >= end); //結果:5, 3, 1, 0 と表示されます
//他に試した文
//do
//{
// cout<< count << endl;
// count -= step;
// if(count < end){
// count = end; //結果:5, 3, 1, 0, 0, 0 ・・・
// }
//
//} while (count >= end);
//do
//{
// cout<< count << endl;
//
// if(count < end){
// count = end; //結果:5, 3, 1
// }
// count -= step;
//} while (count >= end);
}
他に良い書き方がある、もしくはこうすればもっときれいに書けるなど
アドバイスがいただければ幸いです。
環境 :Windows10上でVisualStudio2012を使用しています。
この掲示板で初めて質問させていただきます。
もう少しきれいな書き方があれば教えていただけないでしょうか
やりたいこと:Startに設定した値から、Endに設定した値までStepの値ずつ繰り返し値を表示したい。
条件:
・StartとEndはかならず表示したい。
->Start = 5, End = 0, Step = 2の場合 : 5, 3, 1 ではなく 5, 3, 1, 0と表示したい
・実際にはdouble型の値を使うので、for文を使いたくない。
現在やりたいことは実質達成できているのですが、個人的に無理やり感があるため、もう少しきれいな書き方があるかどうかを模索している最中です。
[code]
#include <stdio.h>
#include <iostream>
using namespace std;
void main(){
//設定値
double start = 5;
double end = 0;
double step = 2;
//Startの値を代入
double count = start;
do
{
//countの値を表示
cout << count << endl;
//値がendと一致した場合ループを抜ける
if(count == end){
break;
}
//countをStepの値だけ減らす
count -= step;
//countの値がend未満の場合、countの値をendに変更してコンティニュー
if(count < end){
count = end;
continue;
}
} while (count >= end); //結果:5, 3, 1, 0 と表示されます
//他に試した文
//do
//{
// cout<< count << endl;
// count -= step;
// if(count < end){
// count = end; //結果:5, 3, 1, 0, 0, 0 ・・・
// }
//
//} while (count >= end);
//do
//{
// cout<< count << endl;
//
// if(count < end){
// count = end; //結果:5, 3, 1
// }
// count -= step;
//} while (count >= end);
}
[/code]
他に良い書き方がある、もしくはこうすればもっときれいに書けるなど
アドバイスがいただければ幸いです。
環境 :Windows10上でVisualStudio2012を使用しています。