Перейти к содержимому

Was not declared in this scope что за ошибка c

  • автор:

Ошибка «not declared in this scope»

‘arr’ was not declared in this scope ‘sum’ was not declared in this scope такие вот ошибки.(
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main () < .

Ошибка ‘N’ was not declared in this scope
#include <iostream> using namespace std; int N int vvod(int N,int A,int I) < .

Ошибка was not declared in this scope
Как мне её исправить polimorfizm1881.cpp: In function ‘int main()’: polimorfizm1881.cpp:38:29.

Ошибка (not declared in this scope)
Как решить данную проблему? #include <iostream> using namespace std; bool gameOver; const.

3967 / 2877 / 670
Регистрация: 08.06.2007
Сообщений: 9,694
Записей в блоге: 4
3ю и 4ю строчку поменяйте местами.
Любитель чаепитий
3741 / 1798 / 565
Регистрация: 24.08.2014
Сообщений: 6,016
Записей в блоге: 1

ЦитатаСообщение от palva Посмотреть сообщение

3ю и 4ю строчку поменяйте местами.
Это никак не влияет, ведь в объявлении функции мы не используем ничего из пространства имен std .

ЦитатаСообщение от triatri3 Посмотреть сообщение

Пишет что ошибка в 7, 9 и 12 строчках

Правда? А вот мне пишет, что в 20 все 3 ошибки.
А ошибки из-за того, что вы используете не те имена переменных, которые передаете в функцию.
В функцию приходят i, j и k, а вы используете какие-то a, b, c.

87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
Помогаю со студенческими работами здесь

Ошибка was not declared in this scope
main. cpp #include "PoolAllocator.h" . reqs.addr = Allocate(reqs.bytes, 10); .

Ошибка: ‘slojenie’ was not declared in this scope
Почему выдаёт ошибку ? ‘slojenie’ was not declared in this scope #include <iostream> using.

Ошибка ‘Randomize’ was not declared in this scope
Сегодня — первый день, когда я что-то "создаю" на языке с++, поэтому я с ним на "Вы". Собственно.

Ошибка ‘file’ was not declared in this scope
Здравствуйте! Помогите кто чем может) в общем она перезаписывает сначала данные 1.txt в 3.txt, а.

Ошибка: ‘sqrt’ was not declared in this scope
Здравствуйте! У меня такая проблема, во время компилирования выдает такую ошибку: 9 27 E:\Zadacha.

Ошибка: ‘stepen’ was not declared in this scope
Доброе утро гайс 🙂 Подскажите пожалуйста что тут не так #include "Header.h" #include.

У меня несколько ошибок «was not declared in this scope» в коде C++, что делать?

это исходный код программы, хотел написать что-то вроде чата на сокетах. Я попытался скомпилировать код, но он мне выдал несколько ошибок «was not declared in this scope». Вот вывод компилятора:

server.cpp: In function ‘void connecter()’: server.cpp:24:24: error: ‘stopServerRunning’ was not declared in this scope 24 | signal(SIGINT, stopServerRunning); // Это предложение используется для выключения сервера при вводе Ctrl + C | server.cpp:26:9: error: ‘connfd’ was not declared in this scope 26 | connfd = accept(sockfd, NULL, NULL); | ^~~~~~ server.cpp:26:25: error: ‘sockfd’ was not declared in this scope; did you mean ‘socket’? 26 | connfd = accept(sockfd, NULL, NULL); | ^~~~~~ | socket server.cpp: In function ‘void listener()’: server.cpp:39:15: error: ‘buff’ was not declared in this scope 39 | bzero(buff, BUFFSIZE); | ^~~~ server.cpp:41:14: error: ‘connfd’ was not declared in this scope 41 | recv(connfd, buff, BUFFSIZE - 1, 0); | ^~~~~~ server.cpp: In function ‘void sender()’: server.cpp:54:21: error: ‘buff’ was not declared in this scope 54 | scanf("%s", buff); | ^~~~ server.cpp:55:14: error: ‘connfd’ was not declared in this scope 55 | send(connfd, buff, strlen(buff), 0); | ^~~~~~

я думаю, что все эти ошибки идут из одной проблемы, но не могу понять откуда

  • Вопрос задан более года назад
  • 1037 просмотров

Arduino.ru

ЕвгенийП аватар

Вам же сказали «как положено». Идите в ЭТОТ раздел форума и ищите там тему про вставку кода, если сами не в состоянии слово code в шапке окна сообщения разглядеть.

  • Войдите на сайт для отправки комментариев

Пт, 04/05/2018 — 21:32
Зарегистрирован: 26.05.2017

я ж вам написал — вставьте код правильно! Кому нафик нужно читать эту простыню?

По делу — так и не увидел, где у вас обьявлена переменная results. Похоже, что нигде. Поэтому и ошибка.

Сдается мне, что вы этот код либо где-то скопировали неправильно, либо собрали из двух-трех других, плохо понимая, что вы делаете.

  • Войдите на сайт для отправки комментариев

Пт, 04/05/2018 — 21:34

Ворота аватар

Зарегистрирован: 10.01.2016
Viktor911 пишет:

«‘results’ was not declared in this scope поскажите что имеется ввиду?

Viktor911 пишет:

я новичек если че)

  • Войдите на сайт для отправки комментариев

Пт, 04/05/2018 — 21:37
Зарегистрирован: 04.05.2018

абсолютно верно вам сдается. написал с книжки к машине, плохо понимая что к чему. то что данная команда не возвращает в начало ясно, где не дописал? вроде все перепроверил, ничего не пропустил.

  • Войдите на сайт для отправки комментариев

Пт, 04/05/2018 — 21:56
Зарегистрирован: 26.05.2017
Viktor911 пишет:

то что данная команда не возвращает в начало

э-э-э, похоже у тебя еще и с английским проблемы, и в программировании ты не сечешь. Тогда я даж не знаю, чем тебе помочь. «Даннная команда» никуда возвращать не должна. Тебе компьютер пишет, что переменнная results не обьявлена — но, похоже, для тебя это ничего не значит.

Я для тебя вижу три варианта:

1) Если прокатит — скопировать код еще раз и хорошенько проверить, чтоб ничего не потерять.

2) Начать изучение программирования с более простоых программ — если не бросишь, через полгода-год дорастешь до уровня этого кода.

3) Забить на это дело

  • Войдите на сайт для отправки комментариев

Пт, 04/05/2018 — 22:02
Зарегистрирован: 04.05.2018

#include #include #include #define RECV_PIN 12 IRrecv irrecv(RECV_PIN); #define IR_Go 0x00ff629d #define IR_Back 0x00ffa857 #define IR_Left 0x00ff22dd #define IR_Right 0x00ffc23d #define IR_Stop 0x00ff02fd #define IR_Servo_L 0x00ff6897 #define IR_Servo_R 0x00ff9867 #define IR_Speed_UP 0x00ffb04f #define IR_Speed_DOWN 0x00ff30cf #define IR_XunJi_Mode 0x00ff18e7 #define IR_Self_Control 0x00ff7a85 #define IR_IR_Control 0x00ff10ef #define IR_Bluetooth_Control 0x00ff38c7 #define IR_ESC 0x00ff52ad ////////////////// #define SensorLeft 6 #define SensorMiddle 9 #define SensorRight 11 unsigned char SL; unsigned char SM; unsigned char SR; int inputPin=A0; int outputPin=A1; unsigned char Bluetooth_val; LiquidCrystal_I2C lcd(0x27,16,2); #define Lpwm_pin 5 #define Rpwm_pin 10 int pinLB=2; int pinLF=4; int pinRB=7; int pinRF=8; unsigned char Lpwm_val=250; unsigned char Rpwm_val=250; int Car_state=0; int servopin=3; int myangle; int pulsewidth; unsigned char DuoJiao=60; void Sensor_IO_Config() < pinMode(SensorLeft,INPUT); pinMode(SensorMiddle,INPUT); pinMode(SensorRight,INPUT); >void Sensor_Scan(void) < SL = digitalRead(SensorLeft); SM = digitalRead(SensorMiddle); SR = digitalRead(SensorRight); >void servopulse(int servopin,int myangle) < pulsewidth=(myangle*11)+500; digitalWrite(servopin,HIGH); delayMicroseconds(pulsewidth); digitalWrite(servopin,LOW); delay(20-pulsewidth/1000); >void Set_servopulse(int set_val) < for(int i=0;i<=10;i++) servopulse(servopin,set_val); >void M_Control_IO_config(void) < pinMode(pinLB,OUTPUT); pinMode(pinLF,OUTPUT); pinMode(pinRB,OUTPUT); pinMode(pinRF,OUTPUT); pinMode(Lpwm_pin,OUTPUT); pinMode(Rpwm_pin,OUTPUT); >void Set_Speed(unsigned char Left,unsigned char Right) < analogWrite(Lpwm_pin,Left); analogWrite(Rpwm_pin,Right); >void advance() < digitalWrite(pinRB,LOW); digitalWrite(pinRF,HIGH); digitalWrite(pinLB,LOW); digitalWrite(pinLF,HIGH); Car_state=1; show_state(); >void turnR() < digitalWrite(pinRB,LOW); digitalWrite(pinRF,HIGH); digitalWrite(pinLB,HIGH); digitalWrite(pinLF,LOW); Car_state=4; show_state(); >void turnL() < digitalWrite(pinRB,HIGH); digitalWrite(pinRF,LOW); digitalWrite(pinLB,LOW); digitalWrite(pinLF,HIGH); Car_state=3; show_state(); >void stopp() < digitalWrite(pinRB,HIGH); digitalWrite(pinRF,HIGH); digitalWrite(pinLB,HIGH); digitalWrite(pinLF,HIGH); Car_state=5; show_state(); >void back() < digitalWrite(pinRB,HIGH); digitalWrite(pinRF,LOW); digitalWrite(pinLB,HIGH); digitalWrite(pinLF,LOW); Car_state=2; show_state(); >void show_state(void) < lcd.setCursor(0,1); switch(Car_state) < case 1:lcd.print("Go ");Serial.print("\r\n GO"); break; case 2:lcd.print("Back ");Serial.print("\r\n Back"); break; case 3:lcd.print("Left ");Serial.print("\r\n Left"); break; case 4:lcd.print("Right ");Serial.print("\r\n Right"); break; case 5:lcd.print("Stop ");Serial.print("\r\n Stop"); break; default: break; >> void LCD1602_init(void) < lcd.init(); delay(10); lcd.backlight(); lcd.clear(); >void Show_V(unsigned char V) < lcd.setCursor(11,0); lcd.print("V= "); lcd.setCursor(13,0); lcd.print(V,DEC); Serial.print("\n Speed= "); Serial.print(V,DEC); >void Show_DuoJiao(unsigned char Jiao) < lcd. setCursor(6,1); lcd.print("C= "); lcd.setCursor(8,1); lcd.print(Jiao,DEC); Serial.print("\n JiaoDu= "); Serial.print(Jiao,DEC); >void Xunji_Mode(void) < lcd.setCursor(0,0); lcd.print("Xunji_Mode "); Sensor_Scan(); if(SM==HIGH) < if(SL==LOW&SR==HIGH) < turnR(); >else if(SR==LOW&SL==HIGH) < turnL(); >else < advance(); >> else < if(SL==LOW&SR==HIGH) < turnR(); >else if(SR==LOW&SL==HIGH) < turnL(); >else < back(); delay(100); stopp(); >> > void Self_Control(void) < int H; lcd.setCursor(0,0); lcd.print("Self_Ctr "); Show_V(Lpwm_val); Set_servopulse(DuoJiao); Show_DuoJiao(DuoJiao); H=Ultrasonic_Ranging(1); delay(300); if(Ultrasonic_Ranging(1)<35) < stopp(); delay(100); back(); delay(50); >if(Ultrasonic_Ranging(1)<60) < stopp(); delay(100); Set_servopulse(5); Show_DuoJiao(5); int L=ask_pin_L(2); delay(300); Set_servopulse(177); Show_DuoJiao(177); int R=ask_pin_R(3); delay(300); if(ask_pin_L(2)>ask_pin_R(3)) < back(); delay(100); turnL(); delay(400); stopp(); delay(50); Set_servopulse(DuoJiao); Show_DuoJiao(DuoJiao); H=Ultrasonic_Ranging(1); delay(500); >if(ask_pin_L(2) <=ask_pin_R(3)) < back(); delay(100); turnR(); delay(400); stopp(); delay(50); Set_servopulse(DuoJiao); Show_DuoJiao(DuoJiao); H=Ultrasonic_Ranging(1); delay(300); >if(ask_pin_L(2) <35&&ask_pin_R(3)<35) < stopp(); delay(50); back(); delay(50); >> else < advance(); >> int Ultrasonic_Ranging(unsigned char Mode) < int old_distance; digitalWrite(outputPin,LOW); delayMicroseconds(2); digitalWrite(outputPin,HIGH); delayMicroseconds(10); digitalWrite(outputPin,LOW); int distance=pulseIn(inputPin,HIGH); distance=distance/58; if(Mode==1) < lcd. setCursor(11,1); lcd.print("H= "); lcd.setCursor(13,1); lcd.print(distance,DEC); Serial.print("\n H= "); Serial.print(distance,DEC); return distance; >else return distance; > int ask_pin_L(unsigned char Mode) < int old_Ldistance; digitalWrite(outputPin,LOW); delayMicroseconds(2); digitalWrite(outputPin,HIGH); delayMicroseconds(10); digitalWrite(outputPin,LOW); int Ldistance=pulseIn(inputPin,HIGH); Ldistance=Ldistance/58; if(Mode==2) < lcd. setCursor(11,1); lcd.print("L= "); lcd.setCursor(13,1); lcd.print(Ldistance,DEC); Serial.print("\n L= "); Serial.print(Ldistance,DEC); return Ldistance; >else return Ldistance; > int ask_pin_R(unsigned char Mode) < int old_Rdistance; digitalWrite(outputPin,LOW); delayMicroseconds(2); digitalWrite(outputPin,HIGH); delayMicroseconds(10); digitalWrite(outputPin,LOW); int Rdistance=pulseIn(inputPin,HIGH); Rdistance=Rdistance/58; if(Mode==3) < lcd. setCursor(11,1); lcd.print("R= "); lcd.setCursor(13,1); lcd.print(Rdistance,DEC); Serial.print("\n R= "); Serial.print(Rdistance,DEC); return Rdistance; >else return Rdistance; > void IR_Control(void) < unsigned long Key; lcd.setCursor(0,0); lcd.print("IR_Ctr "); while(Key!=IR_ESC) < if(irrecv.decode(&results)) < Key=results.value; switch(Key) < case IR_Go:advance(); break; case IR_Back:back(); break; case IR_Left:turnL(); break; case IR_Right:turnR(); break; case IR_Stop:stopp(); break; case IR_Servo_L:if(DuoJiao<=180)< DuoJiao+=10; Set_servopulse(DuoJiao); Show_DuoJiao(DuoJiao);>break; case IR_Servo_R:if(DuoJiao-10>=0) < DuoJiao-=10; Set_servopulse(DuoJiao); Show_DuoJiao(DuoJiao);>break; case IR_Speed_UP:if(Rpwm_val+10 <=250&&Rpwm_val+10<=250)< Lpwm_val+=10;Rpwm_val+=10; Set_Speed(Lpwm_val,Rpwm_val); Show_V(Lpwm_val); >break; case IR_Speed_DOWN:if(Rpwm_val-10>=0&&Rpwm_val-10>=0) < Lpwm_val-=10;Rpwm_val-=10; Set_Speed(Lpwm_val,Rpwm_val); Show_V(Lpwm_val); >break; default: break; > irrecv.resume(); > > lcd.clear(); lcd.setCursor(0,0); lcd.print(" Wait Signal "); stopp(); > void Bluetooth_Control() < lcd.setCursor(0,0); lcd.print("xaxaxaxaxaxaxax"); if(Serial.available()) < Bluetooth_val=Serial.read(); switch(Bluetooth_val) < case'U':advance(); break; case'D':back(); break; case'L':turnL(); break; case'R':turnR(); break; case'S':stopp(); break; >> > void setup() < pinMode(servopin,OUTPUT); LCD1602_init(); M_Control_IO_config(); Set_Speed(Lpwm_val,Rpwm_val); Set_servopulse(DuoJiao); pinMode(inputPin,INPUT); pinMode(outputPin,OUTPUT); Serial.begin(9600); lcd.setCursor(0,0); lcd.print(" Wait Signal "); stopp(); >void loop() < if(irrecv.decode(&results)) < if(results.value==IR_XunJi_Mode) < while(IR_XunJi_Mode) < XunJi_Mode(); >> if(results.value==IR_Self_Control) < while(IR_Self_Control) < Self_Control(); >> if(results.value==IR_IR_Control) < while(IR_IR_Control) < IR_Control(); >> if(results.value==IR_Bluetooth_Control) < while(IR_Bluetooth_Control) < Bluetooth_Control(); >> irrecv.resume(); > delay(10); >
  • Войдите на сайт для отправки комментариев

‘was not declared in this scope’ error

So I was writing this simple program to calculate the day of any date using the Gaussian algorithm found here.

#include using namespace std; //Using the Gaussian algorithm int dayofweek(int date, int month, int year ) < int d=date; if (month==1||month==2) else int m=(month+9)%12+1; int product=(d+(2.6*m-0.2)+y+y/4+c/4-2*c); return product%7; > int main()

It’s a very simple program and what’s even more puzzling is the output.

:In function dayofweek(int, int, int)’: :19: warning: unused variable ‘y’ :19: warning: unused variable ‘c’ :21: warning: unused variable ‘y’ :21: warning: unused variable ‘c’ :23: error: ‘y’ was not declared in this scope :25: error: ‘c’ was not declared in this scope 

It says that my variable is unused but then says that it isn’t declared? Could anyone please tell me whats wrong.

80.4k 16 16 gold badges 128 128 silver badges 174 174 bronze badges
asked Apr 7, 2012 at 16:15
699 2 2 gold badges 7 7 silver badges 11 11 bronze badges
Local variables are not visible outside the <> block where they are declared.
Apr 7, 2012 at 16:18

6 Answers 6

The scope of a variable is always the block it is inside. For example if you do something like

if(. ) < int y = 5; //y is created >//y leaves scope, since the block ends. else < int y = 8; //y is created >//y leaves scope, since the block ends. cout  

The solution is to define y outside of the if blocks

int y; //y is created if(. ) < y = 5; >else < y = 8; >cout  

In your program you have to move the definition of y and c out of the if blocks into the higher scope. Your Function then would look like this:

//Using the Gaussian algorithm int dayofweek(int date, int month, int year ) < int y, c; int d=date; if (month==1||month==2) < y=((year-1)%100); c=(year-1)/100; >else < y=year%100; c=year/100; >int m=(month+9)%12+1; int product=(d+(2.6*m-0.2)+y+y/4+c/4-2*c); return product%7; > 

answered Apr 7, 2012 at 16:21
9,031 11 11 gold badges 60 60 silver badges 95 95 bronze badges

Here's a simplified example based on of your problem:

if (test) //end scope 1 else //end scope 2 int x = y;//error, y is not in scope 

In the above version you have a variable called y that is confined to scope 1, and another different variable called y that is confined to scope 2. You then try to refer to a variable named y after the end of the if , and not such variable y can be seen because no such variable exists in that scope.

You solve the problem by placing y in the outermost scope which contains all references to it:

int y; if (test) < y = 1; >else < y = 2; >int x = y; 

I've written the example with simplified made up code to make it clearer for you to understand the issue. You should now be able to apply the principle to your code.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *