반응형
Write a function named rangeOfNumbers that accepts two integers as parameters and prints as console output the sequence of numbers between the two parameters, separated by commas and spaces. Print an increasing sequence if the first parameter's value is smaller than the second; otherwise, print a decreasing sequence. If the two numbers are the same, that number should be printed by itself. Here are some example calls to your function and the resulting expected output:
CallConsole Output
rangeOfNumbers(2, 8); | 2, 3, 4, 5, 6, 7, 8 |
rangeOfNumbers(18, 11); | 18, 17, 16, 15, 14, 13, 12, 11 |
rangeOfNumbers(42, 42); | 42 |
void rangeOfNumbers(int a, int b)
{
if (b > a)
{
for (int i = a; i <= b; i++)
{
if (i == b)
{
std::cout << i;
return;
}
std::cout << i << ", ";
}
}
else
{
for (int i = a; i >= b; i--)
{
if (i == b)
{
std::cout << i;
return;
}
std::cout << i << ", ";
}
}
}
입력받는 매개변수가 a 가 클 때와 작을 때를 if 문으로 걸러줘서 간단하게 구현했다.
반응형
'학교 과제' 카테고리의 다른 글
indexOf () (0) | 2023.04.04 |
---|---|
rangeOfNumbers() (0) | 2023.04.04 |