c++ - 使用数组和布尔值在输出未知时从输出中删除逗号
问题描述
如何删除输出末尾的逗号。但是在这里我不知道最终输出是什么,因为数组的元素是由用户输入的。所以最后一个数组可以是奇数也可以是偶数,并且它是未知的。我可以使用布尔值、数组和决策。我不允许使用指针或结构,因为我没有学过。
#include<iostream>
using namespace std;
int main()
{
int array[100], Number;
cout << "\nEnter the size of an array (1-20):";
cin >> Number;
if (Number <= 20 && Number > 0)
{
cout << "Enter the elements of the array: \n";
// For loop execution
// i start at 0. as long as i < Number. i++
for (int i = 0; i < Number; i++)
{
cout << "array element " << i << ":";
cin >> array[i];
}
cout << "\nEven Numbers are : ";
// For loop execution
for (int i = 0; i < Number; i++)
{
// condition and execution
if (array[i] % 2 == 0)
{
cout << array[i];
cout << " , ";
}
}
cout << endl;
cout << "odd Numbers are: ";
// For loop execution
for (int i = 0; i < Number; i++)
{
// condition and execution
if (array[i] % 2 != 0)
{
cout << array[i];
cout << " , ";
}
}
cout << endl;
cout << "-------------------------------------------------";
}
else
{
cout << "size is invalid" << endl;
}
system("pause");
return 0;
}
我查看了其他一些程序,但无法弄清楚。我是初学者,所以你能帮我解决这个问题。我被要求使用两个布尔变量名称 <<odd count >> 和 <> 并被要求使用两个数组来解决这个问题。一个 <> 和一个 << Odd Arr[]>> 以及我提到的两个布尔值。
解决方案
只需在元素前打印逗号并检查第一个元素:
bool is_first = true;
for (int i = 0; i < Number; i++)
{
// condition and execution
if (array[i] % 2 == 0)
{
if(!is_first)
{
cout << " , ";
}
cout << array[i];
is_first = false;
}
}
推荐阅读
- python - “tempfile.mkdtemp”会生成两个相同的文件吗?
- c++ - 使用 O3 激活的编译标志是什么
- python - 你如何得到一个矩形绘图来延长你在pygame中输入的更多内容?
- linux - 在 For 循环中将列附加到 CSV
- java - Spring MongoDB 填充引用
- r - R:如何根据每个输入列的相同公式输出一列?
- python - 如何检查熊猫数据框列中的子字符串是否存在于同一数据框中另一列的子字符串中?
- docusignapi - DocuSign 收件箱为空,在收件箱中接收确认的设置
- angular - string.replace 在多个属性上的重构思路
- github - 使用个人访问令牌将 Gradle 上的脚本应用于私有(企业)github 存储库