use of conditional operator

Dear sir,
I am a beginner. I am learning how to use conditional operator.
I have a question
a salesman gets a commision at the rate of 15% if sale is more than 20000. if it is less than 20000, he gets 0 commission
my prgramme is

#include<iostream.h>
#include<conio.h>
void main()
{ clrscr();
int sale,com,a;
cout<<"enter the sale in Rs ";
cin >>sale;
a=sale*15/100;
com=(sale>20000)? a: 0 ;
cout<<"com is Rs "<<com;

}
iam using turbo compiler.
for< 20000 it gives correct value but for more it gives negative values or even 0 .
what is wrong
please help
arora sk
Hi

The code works for me in VC++ 2008. Try to move the parentheses to enclose the full conditional statement, i.e. "com=(sale > 20000 ? a : 0)"

HTH
Dear Sir,
Thanks for the reply,
It does not work same problem continues.
regards,
arora
Last edited on
Using the type of int a; to hold the value of a division is always a bad idea. The value can often be negative or 0. Use a double, or cast the values correct when doing the math to avoid this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

using namespace std;

int main() {

  double salesAmount = 0.0;

  cout << "Enter sales amount:";
  cin >> salesAmount;

  cout << "----- Summary ----" << endl;
  cout << "Sales Amount: " << salesAmount << endl;

  double commission = (salesAmount > 20000) ? ((salesAmount * 15) / 100) : 0;
  cout << "Commission: " << commission << endl;

  return 0;
}
Last edited on
Thanks, Sir !
Your suggestion is correct .
I used your code, it works fine.
Encouraged by your idea I changed int in my code to float.
It aso worked.
Moral Whenever there is division dont go for int data type.
regards,
arora
You can use an int to hold the result, but make sure you convert from the double/float to the int correctly. :) But then note an int won't hold any decimal values.
Topic archived. No new replies allowed.