C++中的turbo数组问题
turbo Array issue in C++
我正在使用Turbo c++
我需要将所有包含0的元素向左移动类似于if数组包含以下值20 10 15 7 4 20 2
输出必须是这样-0 0 10 15 4 2
完整的问题是第一部分是将用户输入的数字替换为0,所以我输入20,它们被0替换
原始值->10|20|15|4|20|2|20
我写了一个代码来搜索和替换输出为10|0|15|4|0|2|0的值。现在我需要在左边收集这些0,就像这样0|0|0|10|15|4|2
代码也包括我写的
#include<iostream.h>
#include<conio.h>
void main()
{
int A[100],no,val,found;
clrscr();
cout<<"Enter number of elements you want to insert ";
cin>>no;
for(int i=0;i<no;i++)
{
cout<<"Enter element "<<i+1<<":";
cin>>A[i];
}
cout<<"Enter the number you want to search ";
cin>>val;
for(int j=0; j<no; j++)
{
if(A[j]==val)
A[j]=0;
}
for(int k=0; k<no; k++)
{
cout<<A[k]<<" ";
}
getch();
}
需要一些帮助。
以下是我的建议:
- 不需要
#include <conio.h>
,它是特定于平台的 clrscr()
函数调用会惹恼试图帮助您的人,因为先前的文本被擦除no
变量需要根据数组- 尝试使用
std::cin.ignore(10000, 'n');
而不是getch()
要使用0移动插槽,需要将值从旧位置复制到新位置,其中第一个新位置是零位置。
给定:
0 -->|10|
1 |15|
2 | 0|
3 | 3|
4 | 4|
第一次迭代,将插槽2中的0与插槽2中的15交换:
0 -->|10|
1 |15| --> | 0|
2 | 0| --> |15|
3 | 3|
4 | 4|
第二次迭代,将插槽1中的0与插槽0中的10交换:
0 -->|10| --> | 0|
1 | 0| --> |10|
2 |15|
3 | 3|
4 | 4|
继续迭代,直到上一个槽的值为零值,或者上一个插槽位于数组的开头之前。
提示:您将需要两个索引,现在和以前
编辑1:示例代码
int swap_index = 0;
int search_index = 0;
#define MAX_NUMBERS 6
unsigned int numbers[6] = {10, 15, 0, 3, 4};
for (search_index = 0; search_index < MAX_NUMBERS; ++search_index)
{
if (numbers[search_index] == 0)
{
swap_index = search_index - 1;
while (swap_index > 0)
{
numbers[swap_index + 1] = numbers[swap_index];
numbers[swap_index] = 0;
--swap_index;
}
}
}
这个代码是一个基础。有些问题,如限额检查,是读者的责任来解决。
相关文章:
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 输入std::数组时出现问题
- 类对象数组的问题会导致崩溃
- 传递二维数组时出现问题
- 从 C++ 中的函数返回数组地址问题
- 使用数组时出现问题
- 打印问题.我在数组中打印值时遇到一些问题
- C++:__aligned(__alignof__) 导致字符数组数据出现问题?
- 将字节数组转换为带有字节序问题的指针
- C++ 填充数组时遇到问题
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- 当我尝试通过 arduino 上的引用传递布尔数组时出现问题
- 我正在尝试解决一个需要数组总和值但代码不起作用的问题,我想做这样的事情
- 编写 cin.get() 以接收字符数组时出现问题
- 在 C++ Consol 中的数组中执行用户命令时出现问题
- 存储另一个函数返回的布尔数组时遇到问题
- 当我在 CLion 中读取数组中的 txt 文件时C++编码问题
- 运行时C++数组初始化问题
- 我在解决此错误时遇到问题.我正在努力在主函数中传递数组