C++入门第5版练习1.19 "The If Statement"的误解 ?
Misunderstanding C++ Primer 5th Edition Exercise 1.19 "The If Statement"?
每个人。在C++初级读本第5版的练习1.19中,它对说
Revise the program you wrote for the exercises in 1.4.1 (p.
13) that printed a range of numbers so that it handles input in which the first
number is smaller than the second
我的代码在运行时似乎符合要求:
#include <iostream>
int main()
{
std::cout << "Enter two numbers: " << std::endl;
int v1 = 0, v2 = 0;
std::cin >> v1 >> v2;
if (v1 < v2) {
while (v1 <= v2) {
std::cout << v1 << std::endl;
++v1;
}
}
else {
std::cout << "First number is bigger." << std::endl;
}
return 0;
}
然而,当我检查两个不同的网站来检查我的答案时,它们在if语句中都有不同的语句:
// Print each number in the range specified by two integers.
#include <iostream>
int main()
{
int val_small = 0, val_big = 0;
std::cout << "please input two integers:";
std::cin >> val_small >> val_big;
if (val_small > val_big)
{
int tmp = val_small;
val_small = val_big;
val_big = tmp;
}
while (val_small <= val_big)
{
std::cout << val_small << std::endl;
++val_small;
}
return 0;
}
两个答案似乎都有一个temp-int变量,我不确定它如何或为什么更适合这个问题。
正在修订的练习为:
编写一个程序,提示用户输入两个整数。打印这两个整数指定范围内的每个数字。
当练习1.19要求你改变程序;手柄";输入第一个数字较小的地方,这意味着程序仍然应该打印该范围内的每个数字。我还认为这个练习是假设你的早期版本的程序只有在第一个数字大于或等于第二个数字的情况下才有效。
换句话说,您需要编写一个程序,其中以下两个输入的输出相同:
输入:5 10
输出:5 6 7 8 9 10输入:10 5
输出:5 6 7 8 9 10
您展示的示例解决方案是通过检查输入数字是否按特定顺序排列来实现这一点,如果不是,则交换它们。这样可以确保这两个值按照程序其余部分所期望的顺序。
我想任务中应该是"如果第一个数字大于第二个",因为另一种情况已经在您的代码中处理了,而这一种情况只是打印一条错误消息。
在这个例子中,如果第一个值大于第二个值,它们只交换值。
我尝试了我的代码版本,它看起来像这样:
//enter code here
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
//write a program that prompts the user for 2 integers
// print each number in the range specifies by those 2 integers
int val1 = 0, val2 = 0;
cout << "Enter 2 integer values: ";
cin >> val1 >> val2;
cout << endl;
// my reason for using if is to always make sure the values are in incrementing order
if (val1 > val2)
{
for (int i = val2; i <= val1; ++i)
cout << i << " ";
}
else
{
for (int i = val1; i <= val2; ++i)
cout << i << " ";
}
cout << endl;
`
无论你的输入是5 10还是10 5:你的输出永远是:5 6 7 8 9 10。
相关文章:
- 我的简单if-else语句是如何无法访问的代码
- 如何将enable-if与模板参数和参数包一起使用
- 无论条件是否为true,if总是在c++中执行
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- Insert函数不适用于2 if语句C++
- If语句未被求值C++
- C++嵌套if语句,基本货币交换
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 是否可以使用if constexpr删除控制流语句
- 要与"if constexpr"一起使用的编译时消息(在预处理器之后)
- 如何删除peer if else分支中的冗长句子
- 我似乎对if/else的基本语句有问题:/
- if数组上的随机数
- 将按位if条件转换为普通if条件
- If语句在c++中被忽略
- 比较if语句中的数组值和int值
- 使用if-else将数字转换为单词
- "The C++ Programming Language 4ed." [Stroustrup 2013] 具体类:"if the representation changes significan
- C++入门第5版练习1.19 "The If Statement"的误解 ?
- [conv]/6 中"The expression e is used as a glvalue if and only if the initialization uses it as a glva