Ik heb de volgende fout in mijn calculatorcode en begrijp niet hoe u het kunt corrigeren. Gelieve enig advies zou nuttig zijn.
FOUT:
Fout: spring naar case label [-Fpermissive] |
FOUT: Kruist initialisatie van ‘int som’ |
FOUT: ‘EXIT’ is niet aangegeven in deze reikwijdte |
Code:
#include <iostream>
#include <cmath>
using namespace std;
void display_menu();
int get_menu_choice();
void get_two_numbers(int &a, int &b);
int add(int a, int b);
int subtract(int a, int b);
int main()
{
int choice;
do
{
display_menu();
choice = get_menu_choice();
int x, y;
switch (choice)
{
case 1: get_two_numbers(x, y);
int sum = add(x, y);
cout << x << " + " << y << " = " << sum << endl;
break;
case 2: get_two_numbers(x, y);
int diff = subtract(x, y);
cout << x << " - " << y << " = " << diff << endl;
break;
default:;
}
} while (choice != 3);
cout << "Good bye...now." << endl;
return 0;
}
void display_menu()
{
cout << endl;
cout << "Simple Calculator Menu" << endl;
cout << "----------------------" << endl;
cout << " 1. Addition (+) " << endl;
cout << " 2. Subtraction (-) " << endl;
cout << " 3. Quit to exit the program" << endl;
cout << endl;
}
int get_menu_choice()
{
int choice;
cout << "Enter your selection (1, 2, or 3): ";
cin >> choice;
while(((choice < 1) || (choice > 3)) && (!cin.fail()))
{
cout << "Try again (1, 2, or 3): ";
cin >> choice;
}
if (cin.fail())
{
cout << "Error: exiting now ... " << endl;
exit(1);
}
return choice;
}
void get_two_numbers(int &a, int &b)
{
cout << "Enter two integer numbers: ";
cin >> a >> b;
}
int add(int a, int b)
{
return (a + b);
}
int subtract(int a, int b)
{
return (a - b);
}
Antwoord 1, Autoriteit 100%
U verklaart nieuwe variabelen in een case-statement zonder een omsluitingsbereik te maken:
switch (choice)
{
case 1: get_two_numbers(x, y);
//* vv here vv *
int sum = add(x, y);
//* ^^ here ^^ */
cout << x << " + " << y << " = " << sum << endl;
break;
case 2: get_two_numbers(x, y);
//* vv here vv */
int diff = subtract(x, y);
//* ^^ here ^^ */
cout << x << " - " << y << " = " << diff << endl;
break;
default:;
}
Hier is het herstellen van het:
switch (choice)
{
case 1:
{
get_two_numbers(x, y);
int sum = add(x, y);
cout << x << " + " << y << " = " << sum << endl;
}
break;
case 2:
{
get_two_numbers(x, y);
int diff = subtract(x, y);
cout << x << " - " << y << " = " << diff << endl;
}
break;
default:
break;
}
Natuurlijk is de exacte opmaak van beugels en inkeping aan u.
Antwoord 2, Autoriteit 27%
Een “Case” van een schakelaar maakt geen scope, dus, zoals de fout zegt, jullie springt over de initialisatie van “Sum” als de keuze niet 1 is.
U hoeft ofwel de som en diff buiten de schakelaar te declareren of blokken met {} voor elk van de gevallen te maken.
Antwoord 3, Autoriteit 5%
U moet variabelen buiten de schakelafschrift aangeven en niet in een geval. In het bijzonder sum
EN diff
zijn problematisch in uw code. Zodra deze variabelen buiten de schakelinstantie worden geïnitialiseerd, kunt u vervolgens hun waarden instellen.