I have the following error in my Calculator code and do not understand how to correct it. Please any advice would be helpful.
ERROR:
error: jump to case label [-fpermissive]|
error:crosses initialization of ‘int sum’|
error: ‘exit’ was not declared in this scope|
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);
}
Offline
Зарегистрирован: 30.03.2015
Здравствуйте господа! Сразу скажу — я только учусь. Нашел на просторах скетч (здесь уже с моими вставками!)
// https://youtu.be/_hnk5jNTudk Low power NeoPixel goggles example. Makes a nice blinky display // with just a few LEDs on at any time. #include <Adafruit_NeoPixel.h> #define PIN 1 Adafruit_NeoPixel pixels = Adafruit_NeoPixel(48, PIN); uint8_t mode = 0, // Эффект по умолчанию offset = 0; // Position of spinny eyes uint32_t color = 0xFF0000; // Start red uint32_t prevTime; //Путь пикселей при змейке - 48 всего int sine[] = {20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0,23,22,21,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,24,25,26,27}; int sine2[] = {20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0,23,22,21,27,26,25,24,47,46,46,44,43,42,41,40,39,38,37,36,35,34,33,32,31,30,29,28}; void setup() { pixels.begin(); pixels.setBrightness(120); // Пол яркости prevTime = millis(); } void loop() { uint8_t i; uint32_t t; switch(mode) { case 0: // Хаотичные блики - вспышки разных диодов в разное время! i = random(48); pixels.setPixelColor(i, color); pixels.show(); delay(10); pixels.setPixelColor(i, 0); break; case 1: // Spinny wheels (8 LED одновременно) for(i=0; i<24; i++) { uint32_t c = 0; if(((offset + i) & 7) < 2) c = color; // 4 pixels on... pixels.setPixelColor( i, c); // Первое очко pixels.setPixelColor(47-i, c); // Второе очко (инверсия) } pixels.show(); offset++; delay(50); break; case 2: //Змейка int r = random(255); int g = random(255); int b = random(255); for(int i=0; i<48; i++) { pixels.setPixelColor(sine[i], pixels.Color(0, 0, 0)); for (int j=0; j<8; j++){ pixels.setPixelColor(sine[(j+i+1)%48], pixels.Color(r, g, b)); //random RGB color value } pixels.show(); delay(80); } break; } t = millis(); if((t - prevTime) > 8000) { // Каждые< 8 seconds... mode++; // Следующий уровень if(mode > 2) { // Последний уровень? mode = 0; // Уровни сначала color >>= 8; // Следующий цвет R->G->B if(!color) color = 0xFF0000; // Сброс на красный } for(i=0; i<48; i++) pixels.setPixelColor(i, 0); prevTime = t; } } // Input a value 0 to 255 to get a color value. // The colours are a transition r - g - b - back to r. uint32_t Wheel(byte WheelPos) { WheelPos = 255 - WheelPos; if(WheelPos < 85) { return pixels.Color(255 - WheelPos * 3, 0, WheelPos * 3); } else if(WheelPos < 170) { WheelPos -= 85; return pixels.Color(0, WheelPos * 3, 255 - WheelPos * 3); } else { WheelPos -= 170; return pixels.Color(WheelPos * 3, 255 - WheelPos * 3, 0); } }
для двух Adafruit WS2812b колец. Скетч запускается и работает. Решил добавить еще один эффект Змейка2. Добавил sine2, изменил «if(mode > 3) { // Последний уровень?» и написал еще один case 3: //Змейка2
case 3: //Змейка2 int r = random(255); int g = random(255); int b = random(255); for(int i=0; i<48; i++) { pixels.setPixelColor(sine2[i], pixels.Color(0, 0, 0)); for (int j=0; j<8; j++){ pixels.setPixelColor(sine2[(j+i+1)%48], pixels.Color(r, g, b)); //random RGB color value } pixels.show(); delay(80); } break;
Но не хочет работать. Пишет огромное количество букв!
C:DocumentsArduinoMad_scientist_gogglesMad_scientist_goggles.ino: In function 'void loop()': Mad_scientist_goggles:61: error: jump to case label [-fpermissive] case 3: // Zmeyka2 ^ Mad_scientist_goggles:51: error: crosses initialization of 'int b' int b = random(255); ^ Mad_scientist_goggles:50: error: crosses initialization of 'int g' int g = random(255); ^ Mad_scientist_goggles:49: error: crosses initialization of 'int r' int r = random(255); ^ Mad_scientist_goggles:62: error: redeclaration of 'int r' int r = random(255); ^ Mad_scientist_goggles:49: error: 'int r' previously declared here int r = random(255); ^ Mad_scientist_goggles:63: error: redeclaration of 'int g' int g = random(255); ^ Mad_scientist_goggles:50: error: 'int g' previously declared here int g = random(255); ^ Mad_scientist_goggles:64: error: redeclaration of 'int b' int b = random(255); ^ Mad_scientist_goggles:51: error: 'int b' previously declared here int b = random(255); ^ exit status 1 jump to case label [-fpermissive]
и останавливается при проверке. Помогите пожалуйста вставить этот case в код!
switch(foo) {
case 1:
int i = 42; // i exists all the way to the end of the switch
dostuff(i);
break;
case 2:
dostuff(i*2); // i is *also* in scope here, but is not initialized!
}
click below button to copy the code. By c++ tutorial team
switch(foo) {
case 1:
{
int i = 42; // i only exists within the { }
dostuff(i);
break;
}
case 2:
dostuff(123); // Now you cannot use i accidentally
}
click below button to copy the code. By c++ tutorial team
switch(choice)
{
case 1: {
// .......
}break;
case 2: {
// .......
}break;
case 3: {
// .......
}break;
}
click below button to copy the code. By c++ tutorial team
Loading
Punk_Joker 1 / 1 / 1 Регистрация: 24.11.2013 Сообщений: 59 |
||||
1 |
||||
01.05.2015, 02:12. Показов 7664. Ответов 4 Метки нет (Все метки)
Проблема в фунциии prim начиная с ветки case NAME. Пишу в CodeBlocks+MinGW. Кликните здесь для просмотра всего текста
Лог компиляции Кликните здесь для просмотра всего текста
||=== Build: Debug in Hello (compiler: GNU GCC Compiler) ===|
0 |
Tulosba 4773 / 3267 / 497 Регистрация: 19.02.2013 Сообщений: 9,046 |
||||
01.05.2015, 09:27 |
2 |
|||
Нужно добавить фигурные скобки внутрь case’ов:
и т.д.
0 |
0 / 0 / 1 Регистрация: 29.05.2017 Сообщений: 16 |
|
02.06.2017, 18:16 |
3 |
Обьясни в чем дело, к чему эти скобки в кейсах? Я столкнулся с такой же ошибкой.
0 |
DrOffset 17460 / 9287 / 2269 Регистрация: 30.01.2014 Сообщений: 16,264 |
||||
02.06.2017, 18:40 |
4 |
|||
Обьясни в чем дело, к чему эти скобки в кейсах? Объясняю «на пальцах»: switch — работает как goto, и каждая из меток case не вносит своей собственной области видимости, т.е. все, что ты объявляешь внутри switch, будет сквозняком видно в нижестоящих case`ах. Из-за этого, если мы не сделаем сами область видимости посредством {}, то мы вынуждены будем перепрыгивать через инициализацию, получая обращение к невалидному объекту. Поэтому компилятор такое запрещает. Вот это же на примере:
0 |
TheCalligrapher Вездепух 10982 / 5965 / 1630 Регистрация: 18.10.2014 Сообщений: 14,962 |
||||
02.06.2017, 18:46 |
5 |
|||
Обьясни в чем дело, к чему эти скобки в кейсах? Я столкнулся с такой же ошибкой. В языке С++ запрещается «прыгать» в область видимости локальной переменной в обход ее объявления с инициализатором
А делается ли такой «прыжок» через
0 |