0

i am learning c++ , student of first semester,

I am trying to divide 2 arrays in loop and store its result in 3rd array that's not working.All other operations work except division following is my code

#include<iostream>
using namespace std;
int main(){
int arr[6]={10,20,30,40,50,06};
int arr2[6]={10,20,20,30,40,50};
int input;
cout<<"please enter 1 for addition.... "<<endl;
cout<<"please enter 2 for subtraction.... "<<endl;

cout<<"please enter 3 for multiplication.... "<<endl;
cout<<"please enter 4 for division.... "<<endl;
cout<<"please enter 5 for %age...."<<endl;
cin>>input;
float arr3[6];

int i,j,k,l,m;

switch(input){
case 1: 
 for(i=0;i<6;i++){

 arr3[i]=arr[i]+arr2[i]  ;
  cout<<arr3[i]<<endl;

 }
 break;
case 2:
 for(j=0;j<6;j++){
  arr3[j]=arr[j]-arr2[j];
  cout<<arr3[j]<<endl;

  }
  break;
case 3:
 for(k=0;k<6;k++){
  arr3[k]=arr[k]*arr2[k];
  cout<<arr3[k]<<endl;

 }
 break;
case 4:
 for(l=0;l<6;l++){
  arr3[l]=arr[l]/arr2[l];
  cout<<arr3[l]<<endl;

 }
 break;
case 5:
 for(m=0;m<6;m++){
  arr3[m]=arr[m]/(arr[m]+arr2[m]);
  cout<<arr3[m]<<endl;

 }
 break;
}

}

for division output is :

1
1
1
1
1
0

i tired to set its data type as dobule and float both but its not working need your help please.

Ali Nawaz
  • 43
  • 1
  • 7

1 Answers1

0

You need to cast the operands before you divide, or else it will use integer division, which has its decimal shaved off. Using c-style casts, it would look like:

arr3[l]= (double)arr[l] / (double)arr2[l];

Note, C++ has its own casting syntax, but it's been awhile since I've used them, and can't remember them exactly. I think it would look like:

arr3[l] = static_cast<double>(arr[l])
          / static_cast<double>(arr2[l]);
Carcigenicate
  • 43,494
  • 9
  • 68
  • 117