C Programa sukurti paprastą skaičiuoklę naudojant jungiklį ... atvejis

Šiame pavyzdyje išmoksite sukurti paprastą skaičiuoklę programuojant C, naudodami jungiklio teiginį.

Norėdami suprasti šį pavyzdį, turėtumėte žinoti šias C programavimo temas:

  • C jungiklio pareiškimas
  • C pertrauka ir toliau

Ši programa +, -, *, /iš vartotojo paima aritmetinį operatorių ir du operandus. Tada jis atlieka dviejų operandų skaičiavimus, priklausomai nuo vartotojo įvesto operatoriaus.

Paprasta skaičiuoklė, naudojant jungiklį

#include int main() ( char operator; double first, second; printf("Enter an operator (+, -, *,): "); scanf("%c", &operator); printf("Enter two operands: "); scanf("%lf %lf", &first, &second); switch (operator) ( case '+': printf("%.1lf + %.1lf = %.1lf", first, second, first + second); break; case '-': printf("%.1lf - %.1lf = %.1lf", first, second, first - second); break; case '*': printf("%.1lf * %.1lf = %.1lf", first, second, first * second); break; case '/': printf("%.1lf / %.1lf = %.1lf", first, second, first / second); break; // operator doesn't match any case constant default: printf("Error! operator is not correct"); ) return 0; ) 

Rezultatas

Įveskite operatorių (+, -, *,): * Įveskite du operandus: 1,5 4,5 1,5 * 4,5 = 6,8 

Vartotojo *įvestas operatorius saugomas operatoriuje. Ir abu operandai, 1.5ir 4.5yra saugomi pirmas ir antras atitinkamai.

Kadangi operatorius *sutampa case '*':, programos valdymas pereina į

printf("%.1lf * %.1lf = %.1lf", first, second, first * second); 

Šis teiginys apskaičiuoja produktą ir parodo jį ekrane.

Galiausiai break;pareiškimas baigia switchteiginį.

Įdomios straipsniai...