Hello I am new to C++ and I have been experimenting and one program I wrote acts weird... Let me post the code and then I'll explain what is happening.
I apologize for any words misspelled english is my second language, most of the identifiers for the variables or other things that the name doesn't matter are named in spanish
#include <iostream>
#include <string>
using namespace std;
string unidad;
float calcular(float a, float b, float c) {
a = a*12;
b = b*2;
if (c<a, c<b) { unidad = "1 dozen"; return (c); }
else if (b<a, b<c) { unidad = "half dozen"; return (b); }
else if (a<b, a<c) { unidad = "12 units"; return (a); }
else (c==a, c==b); { cout << "everything cost the same, buy 1 dozen for comfort" << "\n"; }
}
int main() {
float precio1, precio6, precio12, result;
cout << "price 1 unit, half dozen, 1 dozen"; cin >> precio1 >> precio6 >> precio12;
result = calcular(precio1, precio6, precio12);
cout << "it is recomended to buy: " << unidad << endl << "it will cost: " << result << endl;
system ("pause > nul");
}
The program is supposed to calculate which price is lower and tell the person what is the best option on how to buy.
The weird thing is that if I put that a unit value is 1 to make it 12, I put the half a dozen value to 7 to make it 14 and the dozen price to 13 it chosses the dozen instead of the unit, but if change the price of half a dozen to 6.5 to make it 13 if chosses the unit. If I maintain the price of the half a dozen to 6.5 to make it 13 and I change the price of the dozen to 14 it chosses the half dozen although the unit price is 1 to make it 12.
You cannot use commas in an if statement in C++ as far as I know (I'm suprised your compiler didn't throw an error). You probably want to use the "logical and" operator, which is two ampersands (&&).
Example: if(c<a && c<b)
This will be true is c is less than a AND c is less than b.
That's one of the things about C++, you can combine syntax in very odd ways - sometimes there are good reasons to do so, but often it just conceals errors and confuses you:-)