Primer C++ 练习1.4.1 编写程序提示用户输入两个整数,打印出这两个整数所指定的范围内的所有整数

本文探讨了在C++中如何根据用户输入的两个整数,输出这两个整数之间的所有整数,包括处理包含和不包含边界情况的两种算法实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    个人认为这个题目出的有点歧义。因为不知道是否连带输入的两个数。所以目前网上基本上有几种解释:

不包含输入的两个数、包含其中一个数、包含输入的两个数。

网上很多代码都是包含其中一个数,要么带上上限 要么带上下限 ,主要是看用的是自加还是自减。

 

这里说一下包含和不包含上下限的情况。

当为包含输入的两个数时:

#include <iostream>
using namespace std;
int main()
{
	int one,one1,one2;
	cout << "请输入两个数 " << endl;
	cin >> one1 >> one2;
	one = one1 - one2;
	if (one == 0)
	{
		cout << "相等整数间无整数\n" << endl;
	}
	else 
	{
		while (one1 > one2) {
			cout << "两整数之间的中间数有: " << one1 << endl;
			one1--;
		}
		while (one1 < one2) {
			cout << "两整数之间的中间数有: " << one1 << endl;
			one1++;

		}
		//打印最后一次--的结果
		cout << "两整数之间的中间数有: " << one1 << endl;
	}
	return 0;
}

上述代码测试:

 

当理解为不包含两个数时:(掐头去尾)

#include <iostream>
using namespace std;
int main()
{
	int one,one1,one2;
	cout << "请输入两个数 " << endl;
	cin >> one1 >> one2;
	one = one1 - one2;
	if (abs(one) <= 1)
	{
		cout << "相邻或相等整数间无整数\n" << endl;
	}
	while (one1 > (one2+1)) {
		one1--;
		cout << "上述两个整数之间的中间数有: " << one1 << endl;
	}
	while ((one1+1) < one2) {
		one1++;
		cout << "上述两个整数之间的中间数有: " << one1 << endl;
	}
	return 0;
}

 上述代码测试:

当one1>one2 和one1<one2 的情况时:

当 |one1-one2 |<=1的情况时:

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值