gpt4 book ai didi

c++ - 如何解决此错误 : jump to case label crosses initialization

转载 作者:IT老高 更新时间:2023-10-28 12:42:13 30 4
gpt4 key购买 nike

我的计算器代码中有以下错误,不知道如何更正。请任何建议都会有所帮助。

错误:错误:跳转到案例标签 [-fpermissive]|错误:跨过“int sum”的初始化|错误:未在此范围内声明“退出”|

代码:

#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);
}

最佳答案

您在 case 语句中声明新变量而不创建封闭范围:

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:;
}

解决方法如下:

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;
}

当然,括号和缩进的确切格式取决于您。

关于c++ - 如何解决此错误 : jump to case label crosses initialization,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23599708/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com