ntx a dit:
Et peut être la façon la plus élégante d'implémenter ce type d'application

A méditer pour ceux qui se demandent depuis 20 ans pourquoi HP s'était aventuré la-dedans pour ces calculatrices :O
Personelement, je préfère cette manière, y a pas 50 parenthèses
Sinon pour le programme c'est plus beau avec un switch plutôt que des elseif non ? :siffle:
Voici un exemple de code d'une calculatrice "complète" mode console

Ca le code d'un de mes cours de l'année passée, on commentait en anglais désolé si tu es anglophobe !!!
IMPORTANT : pour compiler avec gcc, si tu ne stipules pas que c 'est du C99 (qui a certains avantages du c++), gcc va t'envoyer bouler

!!!
Pour compiler : gcc --std=c99 --pedantic lefichier.c
**********************
#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>
static int fastExponentiation(int base, int exponent);
static int fastExponentiation(int base, int exponent)
{
int a = 1;
int b = base;
int c = exponent;
// Loop invariant : a*(b^c) = base^exponent.
while (c) {
if (c % 2)
a = a * b;
b = b * b;
c = c / 2;
}
// Postcondition : c == 0, thus base^exponent = a.
return a;
}
/**
* Main function.
**/
int main()
{
int currentValue;
// Read the first operand
printf("Entrez la valeur initiale : ");
int readArguments;
readArguments = scanf("%d", ¤tValue);
if (readArguments != 1) {
printf("Vous n'avez pas entrÈ un nombre !");
return -1;
}
// Loop forever
while (true) {
// Display the current value
printf("Valeur actuelle : %d\n", currentValue);
printf("Entrez un opÈrateur et une opÈrande : ");
// Read the new operator
int operator;
do {
operator = getchar(); // Try reading a new character
} while (operator != EOF && // Stop when reaching the end of the input
isspace(operator)); // Loop until reaching a non-blank char.
if (operator == EOF) { // The end of the input has been reached
printf("Vous avez mal formattÈ votre opÈrateur !\n");
return -1;
}
if (operator == 'q') // The user wants to stop the calculation
break;
// Read the new operand
int operand;
readArguments = scanf("%d", &operand);
if (readArguments != 1) {
printf("Vous avez mal formattÈ votre opÈrande !\n");
return -1;
}
// Operator handling
switch (operator) {
case '+' : currentValue += operand; break; // Addition case
case '-' : currentValue -= operand; break; // Substraction case
case '*' : currentValue *= operand; break; // Multiplication case
case '/' : // Division case
if (!operand) { // Division by zero handling
printf("Tentative de division par zÈro !\n");
return -1;
}
currentValue /= operand;
break;
case '^' : // Integer power case
if (operand < 0) { // Negative power handling
printf("Elevation ? une puissance nÈgative !\n");
return -1;
}
currentValue = fastExponentiation(currentValue, operand);
break;
default : // Default case : error
printf("OpÈrateur inconnu !\n");
return -1;
}
}
return 0;
}