如何打印结果? [英] How do I have the result printed ?

查看:88
本文介绍了如何打印结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是通过将数组作为对函数的引用来从数组中删除某个元素...但是以下程序在处理后不会打印数组!



我尝试过:



The problem is to remove a certain element from an array by passing array as reference to a function...But the following program doesn't print the array after processing !

What I have tried:

#include<stdio.h>
#define SIZE 50
void rem(int *a,int ele,int size){
	for(int i=0;i<size;i++){
		//i--;
		if(*(a+i)==ele){
			*(a+i)=*(a+i+1);
			size--;
			i--;
		}
	}
	for(int i=0;i<size;i++)
		printf("%d ",*(a+i));
}
void main(){
	int arr[SIZE],ele,n,i;
	printf("size : ");
	scanf("%d",&n);
	for(i=0;i<n;i++){
		printf("Ele : ");
		scanf("%d",&arr[i]);
	}
	printf("Element to be removed : ");
	scanf("%d",&ele);
	rem(arr,ele,n);
	
}

推荐答案

问题是您通过将以下项目复制到其中删除了一个项目但是您没有不对数组中的其余项做任何事情。您需要为数组中的每个后续项重复该移动。否则你所拥有的只是两个项目的重复。
The problem is you removed one item by copying its following item to it but you didn't do anything with the rest of the items in the array. You need to repeat that move for every following item in the array. Otherwise what you have is just a duplication of two items.


尝试

Try
#include <stdio.h>

#define SIZE 50

int rem(int *a,int ele, int size)
{
  int found = 0;

  for(int i=0;i<(size-found);i++)
  {
    if ( ! found )
    {
      if ( *(a+i) == ele)
        found = 1;
    }
    if ( found )
      *(a+i) = *(a+i+1);
  }
  return (size-found); // return the new size of the array
}

int main()
{
  int arr[SIZE], ele, n, i;
  printf("size : ");
  scanf("%d", &n);
  for(i=0; i<n; i++)
  {
    printf("Ele : ");
    scanf("%d",&arr[i]);
  }
  printf("Element to be removed : ");
  scanf("%d", &ele);
  int size = rem(arr, ele, n);
  for (i=0; i<size; ++i)
    printf("Ele[%d] : %d\n", i,arr[i]);
  return 0;
}


这篇关于如何打印结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆