步骤程序?开始,结束,步长整数

时间:2016-04-30 06:29:50

标签: c++ for-loop while-loop

我已经坚持了近两个星期,有人可以指导我吗?我应该让用户输入一个初始起始值,它们想要结束的整数,以及一个步进整数(起始值乘以的是什么)。

EX。 起始整数:10 结束整数:200 步进整数:20

输出:10,30,50,70,90,......,200

当用户输入的错误值比结束整数小于开始整数时,消息会提示他们再试一次。

我得到了整个消息提示我相信,不知道如何让起始整数乘以步进,并停止结束整数。

这是我到目前为止的代码:

#include <iostream>
#include <string>

using namespace std;



int main()
{


int step;           
int stop;   







int start = -1;             //Local variable declaration



cout << "Please enter a positive integer you'd like to start with." << endl;      //Starting integer
cin >> start;


if (start < 0)

cout << "Please enter a positive integer.";


if (start >= 0)

 cout << "Please enter an integer to end with, it must be bigger than    previous number chosen."; //Ending integer
cin >> stop;


if (stop < start)
cout << "Please enter a value that is larger than the previous number chosen." << endl;



if (stop > start)
cout << "Please enter the value you'd like to increase by." << endl; //Stepping integer
cin >> step;



cout << "Integers:";
while (start < stop)
{
    cout << start << ", ";
    start+=step;
}

return 0;

}

当我运行它时,它将遍历整个for循环,并显示while循环,但只显示用户输入的步进整数,然后立即退出。

编辑 - 上面的代码从以前的代码

更新

感谢迄今为止的所有帮助!我已经取出了所提到的for循环,并删除了'cin&gt;&gt;开始;'在“请输入正整数”之后。 - 这就是为什么我的程序没有贯穿整个周期的原因。

如果用户第一次按照说明操作,程序运行完美,但如果他们先输入负值,他们将得到以下结果:

输入:-5 输出:请输入正整数。 输入:5 输出:请输入您想要增加的值。

如果他们输入小于起始值的停止值,他们将得到以下结果:

输入:5 输出:请输入较大的停止值.... 输入:3 输出:整数:.........

即使在用户首先输入负值和/或停止值小于启动后,如何才能让提示按顺序继续?我不认为这是一个cin;命令,但如果我错了请纠正我!

2 个答案:

答案 0 :(得分:1)

也许这会有所帮助:

int start = 10;
int stop = 200;
int step = 20;
do
{
    cout << start << " ";
    start = start + step; // increment. Shorter version: start += step;
} while (start < stop);

获取输入时尝试

int start = -1;

while(start < 0)
{
    cout << "Please enter a positive integer you'd like to start with." << endl;
    cin >> start;
}

并对stopstep执行类似的操作,例如

int end = -1;

while(end < start)
{
     cout << "Please enter an integer to end with, it must be bigger than previous number chosen."; //Ending integer
     cin >> end;
}

答案 1 :(得分:0)

而不是将1开始递增,而是将其递增step

此外,您需要输出start变量,而不是step。像以前一样输出步骤只会导致:

Integer: 20
Integer: 20
Integer: 20
....

以下是我所做的更改:

cout << "Integers: ";
while(start < end)
{
    cout << start << ", ";
    start+=step;
}

此外,不需要for循环,无论如何都会突破它,所以只需删除for循环。