Синтаксическая ошибка return c

#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

const int NUM_GAME = 3;

int main ( void )
{

 int score1 = 0;
 int score2 = 0;
 int score3 = 0;
 int total = 0;
 double average = 0;
 char repeat;
 string name, dummy;

 //Allow user to run program again
 do
 {
//Resets total to process another game if desired
total = 0;

cout << "nBowler #1's name: ? ";   //Reads name
getline(cin, name);

   do
   {
     cout << "nEnter"<<name<<"'s score for each of the following games:";
     cin >> score1;
     cin >> score2;
     cin >> score3;
     if(score1 < 0 || score1 > 300 || score2 < 0 || score2 > 300 || score3 < 0 || score3 > 300 )
       cout << "nn*** INVALID SCORE ENTERED! Please try again. ***";
   while(score1 > -1 && score1 < 301 || score2 > -1 && score2 < 301 || score3 > -1 && score3 <         301);
   total = score1 + score2 + score3;
   }

  cout << setprecision(2) << fixed << showpoint;

//Calcualtes the average sales for the salesperson
average = total / NUM_GAME;
cout << "nnThe bowling average for " << name  << " is " << average << endl << endl;

cout << "nWould you like to calculate the average for another Game? Y or N ";
cin >> repeat;
getline(cin, dummy);
while (repeat == 'y' || repeat == 'Y');
}
return 0;
}

Please excuse the formatting issues and stuff its rough I know
this is coming up with 2 errors:

error C2061: syntax error : identifier 'cout'
error C2059: syntax error : 'return'

like I said it’s rough and the solution is probably something extremely obvious but I’m new and I’m still learning the ropes

Parker's user avatar

Parker

8,52910 gold badges68 silver badges98 bronze badges

asked Oct 25, 2014 at 3:32

Tiffany Elizabeth Beckham's user avatar

2

First of all, indent your code better.

Secondly,

do
{

    while (repeat == 'y' || repeat == 'Y');
}

is probably not what you want.

answered Oct 25, 2014 at 3:39

ipavl's user avatar

ipavlipavl

82811 silver badges20 bronze badges

1

The do...while should be

do
{
  //code
}while(...);

Instead of

do
{
  //code
  while(...);
}

You have to close its body before the while. So modify both your loops and then,the errors will be gone.

answered Oct 25, 2014 at 3:44

Spikatrix's user avatar

SpikatrixSpikatrix

20.2k7 gold badges37 silver badges83 bronze badges

Hey;
I’m kinda new to C++, but I’m getting a syntax error for my return statement in my function. Here’s my code:
// Physics Problem Solver.cpp : Defines the entry point for the console application.
//

#include «stdafx.h»
#include <iostream>
#include <stdlib.h>
#include <windows.h>
#include <conio.h>
#include <string.h>
#include <sstream>

void welcome();
int mainMenu();
void kinematics();
void dynamics();
void cmwe();
void motionAndWaves();

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    welcome();
    return 0;
}

//===========================================================================================================================================================================================================
//Functions
//===========================================================================================================================================================================================================
void welcome()
{
    cout << «Welcome to the Physics 20 Problem Solver. Please select your unit:» << endl;
    int menuSelection = mainMenu();
    system(«PAUSE»);
}
//===========================================================================================================================================================================================================
int mainMenu()
{
    int menuSelection = 1;
    char input = _getch();
    if (int(input) = 31)
        menuSelection++;
    if (int(input) = 30)
        menuSelection—;
    if (menuSelection < 1)
        menuSelection = 1;
    if (menuSelection > 4)
        menuSelection = 4;
    do
    {
        switch(menuSelection)
        {
        case 1:
            cout << «KINEMATICSnDynamicsnCircular Motion, Work, and EnergynOscillary Motion and Mechanical Waves» << endl;
            break;

            case 2:
            cout << «KinematicsnDYNAMICSnCircular Motion, Work, and EnergynOscillary Motion and Mechanical Waves» << endl;
            break;

                    case 3:
            cout << «KinematicsnDynamicsnCIRCULAR MOTION, WORK, AND ENERGYnOscillar Motion and Mechanical Waves» << endl;
            break;

            case 4:
            cout << «KinematicsnDynamicsnCircular Motion, Work, and EnergynOSCILLAR MOTION AND MECHANICAL WAVES» << endl;
            break;
        }
        while (int(input) != 13);
    }
    return menuSelection;
}

I don’t know why I’m getting this error, it’s the only return statement there. When I comment out the return line, I get a syntax error on my last curly brace. What’s wrong with the damn curly brace…I really don’t know. Been sitting here staring at it for an hour, this is the part of programming I hate.

I’ve been looking at c++ for a while now, but all I have been able to do so far is basic console stuff. I wanted to do some more stuff so I started looking at SDL. I installed SDL no problem, but when I tried to follow this (http://pgdc.purdue.org/sdltutorial/01/) tutorial on SDL basics, the output from Visual Studio 2008 was:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
/* -- Include the precompiled libraries -- */
#ifdef WIN32
#pragma comment(lib, "SDL.lib")
#pragma comment(lib, "SDLmain.lib")
#endif

#include <stdlib.h>
#include "SDL.h"

#define TRUE 1
#define FALSE 0

int main(int argc, char *argv[])
{
	SDL_Surface *screen;
	SDL_Surface *picture;
	SDL_Event event;
	SDL_Rect pictureLocation;
	int leftPressed, rightPressed, upPressed, downPressed;
	const SDL_VideoInfo* videoinfo;
	
	atexit(SDL_Quit);

	/* Initialize the SDL library */
	if( SDL_Init(SDL_INIT_VIDEO) < 0 ) {
		fprintf(stderr,"Couldn't initialize SDL: %sn", SDL_GetError());
		exit(1);
	}

	screen = SDL_SetVideoMode(640, 480, 32, SDL_DOUBLEBUF | SDL_HWSURFACE);
	if ( screen == NULL ) {
		fprintf(stderr, "Couldn't set 640x480x8 video mode: %sn",
			SDL_GetError());
		exit(1);
	}
	
	videoinfo = SDL_GetVideoInfo();

	printf("%i", videoinfo->blit_hw);

	// Load Picture
	picture = SDL_LoadBMP("Iapetus.bmp");

	if (picture == NULL) {
		fprintf(stderr, "Couldn't load %s: %sn", "SDL_now.bmp", SDL_GetError());
		return 0;
	}

	while(TRUE) {
		if (leftPressed) {
			if (pictureLocation.x > 0)
				pictureLocation.x--;
		}
		if (rightPressed) {
			if (pictureLocation.x < 640-picture->w)
				pictureLocation.x++;
		}
		if (upPressed) {
			if (pictureLocation.y > 0) {
				pictureLocation.y--;
			}
		}
		if (downPressed) {
			if (pictureLocation.y < 480-picture->h) {
				pictureLocation.y++;
			}
		}

		SDL_FillRect(screen, NULL, 1000);
		SDL_BlitSurface(picture, NULL, screen, &pictureLocation);
		SDL_Flip(screen);

		if( SDL_PollEvent( &event ) ){
		/* We are only worried about SDL_KEYDOWN and SDL_KEYUP events */
		switch( event.type ){
			case SDL_KEYDOWN:
				switch(event.key.keysym.sym) {
					case SDLK_LEFT:
						leftPressed = TRUE;
						break;
					case SDLK_RIGHT:
						rightPressed = TRUE;
						break;
					case SDLK_DOWN:
						downPressed = TRUE;
						break;
					case SDLK_UP:
						upPressed = TRUE;
						break;
					case SDLK_ESCAPE:
						exit(0);
					default:
						break;
			}
				break;
	
				case SDL_KEYUP:
					switch(event.key.keysym.sym) {
						case SDLK_LEFT:
							leftPressed = FALSE;
							break;
						case SDLK_RIGHT:
							rightPressed = FALSE;
							break;
						case SDLK_DOWN:
							downPressed = FALSE;
							break;
						case SDLK_UP:
							upPressed = FALSE;
							break;
						default:
							break;
					}
					break;

					default:
					break;
				}
			}
		}
	}
	return 0;
}

I have no idea why it told me «return» was a syntax error and I had missing «;», having rechecked the whole code twice, and would appreciate any help in resolving my problems.

I’ve been looking at c++ for a while now, but all I have been able to do so far is basic console stuff. I wanted to do some more stuff so I started looking at SDL. I installed SDL no problem, but when I tried to follow this (http://pgdc.purdue.org/sdltutorial/01/) tutorial on SDL basics, the output from Visual Studio 2008 was:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
/* -- Include the precompiled libraries -- */
#ifdef WIN32
#pragma comment(lib, "SDL.lib")
#pragma comment(lib, "SDLmain.lib")
#endif

#include <stdlib.h>
#include "SDL.h"

#define TRUE 1
#define FALSE 0

int main(int argc, char *argv[])
{
	SDL_Surface *screen;
	SDL_Surface *picture;
	SDL_Event event;
	SDL_Rect pictureLocation;
	int leftPressed, rightPressed, upPressed, downPressed;
	const SDL_VideoInfo* videoinfo;
	
	atexit(SDL_Quit);

	/* Initialize the SDL library */
	if( SDL_Init(SDL_INIT_VIDEO) < 0 ) {
		fprintf(stderr,"Couldn't initialize SDL: %sn", SDL_GetError());
		exit(1);
	}

	screen = SDL_SetVideoMode(640, 480, 32, SDL_DOUBLEBUF | SDL_HWSURFACE);
	if ( screen == NULL ) {
		fprintf(stderr, "Couldn't set 640x480x8 video mode: %sn",
			SDL_GetError());
		exit(1);
	}
	
	videoinfo = SDL_GetVideoInfo();

	printf("%i", videoinfo->blit_hw);

	// Load Picture
	picture = SDL_LoadBMP("Iapetus.bmp");

	if (picture == NULL) {
		fprintf(stderr, "Couldn't load %s: %sn", "SDL_now.bmp", SDL_GetError());
		return 0;
	}

	while(TRUE) {
		if (leftPressed) {
			if (pictureLocation.x > 0)
				pictureLocation.x--;
		}
		if (rightPressed) {
			if (pictureLocation.x < 640-picture->w)
				pictureLocation.x++;
		}
		if (upPressed) {
			if (pictureLocation.y > 0) {
				pictureLocation.y--;
			}
		}
		if (downPressed) {
			if (pictureLocation.y < 480-picture->h) {
				pictureLocation.y++;
			}
		}

		SDL_FillRect(screen, NULL, 1000);
		SDL_BlitSurface(picture, NULL, screen, &pictureLocation);
		SDL_Flip(screen);

		if( SDL_PollEvent( &event ) ){
		/* We are only worried about SDL_KEYDOWN and SDL_KEYUP events */
		switch( event.type ){
			case SDL_KEYDOWN:
				switch(event.key.keysym.sym) {
					case SDLK_LEFT:
						leftPressed = TRUE;
						break;
					case SDLK_RIGHT:
						rightPressed = TRUE;
						break;
					case SDLK_DOWN:
						downPressed = TRUE;
						break;
					case SDLK_UP:
						upPressed = TRUE;
						break;
					case SDLK_ESCAPE:
						exit(0);
					default:
						break;
			}
				break;
	
				case SDL_KEYUP:
					switch(event.key.keysym.sym) {
						case SDLK_LEFT:
							leftPressed = FALSE;
							break;
						case SDLK_RIGHT:
							rightPressed = FALSE;
							break;
						case SDLK_DOWN:
							downPressed = FALSE;
							break;
						case SDLK_UP:
							upPressed = FALSE;
							break;
						default:
							break;
					}
					break;

					default:
					break;
				}
			}
		}
	}
	return 0;
}

I have no idea why it told me «return» was a syntax error and I had missing «;», having rechecked the whole code twice, and would appreciate any help in resolving my problems.

Hey;
I’m kinda new to C++, but I’m getting a syntax error for my return statement in my function. Here’s my code:
// Physics Problem Solver.cpp : Defines the entry point for the console application.
//

#include «stdafx.h»
#include <iostream>
#include <stdlib.h>
#include <windows.h>
#include <conio.h>
#include <string.h>
#include <sstream>

void welcome();
int mainMenu();
void kinematics();
void dynamics();
void cmwe();
void motionAndWaves();

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    welcome();
    return 0;
}

//===========================================================================================================================================================================================================
//Functions
//===========================================================================================================================================================================================================
void welcome()
{
    cout << «Welcome to the Physics 20 Problem Solver. Please select your unit:» << endl;
    int menuSelection = mainMenu();
    system(«PAUSE»);
}
//===========================================================================================================================================================================================================
int mainMenu()
{
    int menuSelection = 1;
    char input = _getch();
    if (int(input) = 31)
        menuSelection++;
    if (int(input) = 30)
        menuSelection—;
    if (menuSelection < 1)
        menuSelection = 1;
    if (menuSelection > 4)
        menuSelection = 4;
    do
    {
        switch(menuSelection)
        {
        case 1:
            cout << «KINEMATICSnDynamicsnCircular Motion, Work, and EnergynOscillary Motion and Mechanical Waves» << endl;
            break;

            case 2:
            cout << «KinematicsnDYNAMICSnCircular Motion, Work, and EnergynOscillary Motion and Mechanical Waves» << endl;
            break;

                    case 3:
            cout << «KinematicsnDynamicsnCIRCULAR MOTION, WORK, AND ENERGYnOscillar Motion and Mechanical Waves» << endl;
            break;

            case 4:
            cout << «KinematicsnDynamicsnCircular Motion, Work, and EnergynOSCILLAR MOTION AND MECHANICAL WAVES» << endl;
            break;
        }
        while (int(input) != 13);
    }
    return menuSelection;
}

I don’t know why I’m getting this error, it’s the only return statement there. When I comment out the return line, I get a syntax error on my last curly brace. What’s wrong with the damn curly brace…I really don’t know. Been sitting here staring at it for an hour, this is the part of programming I hate.

I am extremely new to programming (my second week in) and I am trying to understand why when I start without debugging, I keep receiving this error message!

I only receive one error and it is the «c2059» ‘return’ error code.. It’s not descriptive at all, so I have no idea what I did wrong.

I have a picture link available below through google drive to show my code. Any help offered is greatly appreciated!

https://drive.google.com/file/d/0B5hXFZn11VsudXBXRlI3Vjg1OEU/view?usp=sharing

I am also fairly new to this site, if I am breaking any formal etiquette, please let me know as well..

I am using Microsoft Visual Studio 2008.

asked Feb 2, 2015 at 3:01

Julius Verne's user avatar

3

You have some stray text (endl/) at the end of the second last line, which is causing a parsing error.

You also appear to have typed return o; (the letter «o») — as you don’t have a variable called o this will also cause an error. I suspect you meant return 0; instead.

answered Feb 2, 2015 at 3:03

Jonathan Potter's user avatar

Jonathan PotterJonathan Potter

35.8k4 gold badges62 silver badges76 bronze badges

4

I am extremely new to programming (my second week in) and I am trying to understand why when I start without debugging, I keep receiving this error message!

I only receive one error and it is the «c2059» ‘return’ error code.. It’s not descriptive at all, so I have no idea what I did wrong.

I have a picture link available below through google drive to show my code. Any help offered is greatly appreciated!

https://drive.google.com/file/d/0B5hXFZn11VsudXBXRlI3Vjg1OEU/view?usp=sharing

I am also fairly new to this site, if I am breaking any formal etiquette, please let me know as well..

I am using Microsoft Visual Studio 2008.

asked Feb 2, 2015 at 3:01

Julius Verne's user avatar

3

You have some stray text (endl/) at the end of the second last line, which is causing a parsing error.

You also appear to have typed return o; (the letter «o») — as you don’t have a variable called o this will also cause an error. I suspect you meant return 0; instead.

answered Feb 2, 2015 at 3:03

Jonathan Potter's user avatar

Jonathan PotterJonathan Potter

35.8k4 gold badges62 silver badges76 bronze badges

4

knf

17 / 17 / 8

Регистрация: 18.09.2012

Сообщений: 184

1

Синтаксическая ошибка

23.02.2013, 15:31. Показов 4949. Ответов 7

Метки нет (Все метки)


C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include "stdafx.h"
#include <conio.h>
#include <stdio.h>
 
#define eof -1
#define maxline 1000
int getline(char s[] ,int lim);
int main()
{   char s[maxline];
    int y;
    
    printf("Enter your string n");
 
    y=getline(s[],256);
 
    return 0;
}
int getline(char s[], int lim)
{   int c,i;
    
    for (i=0; i<lim-1 && (c=getchar()) != eof && c != 'n'; i++)
        s[i]=c;
        s[i]='';
        i++;
 
    return(i);
}

error C2059: синтаксическая ошибка: ]
Не пойму почему… Точно знаю, что при вызове функции…

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

0

Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

23.02.2013, 15:31

7

The_bolT

73 / 73 / 12

Регистрация: 22.01.2013

Сообщений: 231

23.02.2013, 15:33

2

C++
1
y=getline(s,256);

1

401 / 312 / 74

Регистрация: 17.03.2010

Сообщений: 1,119

23.02.2013, 15:35

3

0

knf

17 / 17 / 8

Регистрация: 18.09.2012

Сообщений: 184

24.02.2013, 15:08

 [ТС]

4

The_bolT, Получилось. Просто я уже убирал эти скобки и выдавало другую ошибку, а тут я написал так

C++
1
int getline(char s[] ,int lim)

а не

C++
1
int getline(char ,int )

и получилось..

Добавлено через 23 часа 31 минуту
Есть еще вопрос, не пойму где ошибки(

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <conio.h>
 
 
float sum();
float razn();
float del();
float proizv();
float degree();
float fact();
 
 
int main()
{   
    
    int x,c;
    float s;
    printf("Bb|bepute deu`ctBue");
    scanf("%d",&c);
    switch(c)
    {
        case '+' : 
            sum(); 
            s=sum();
            break;
        case '-' : 
            razn();
            s=razn();
            break;
        case '/' : 
            del();
            s=fact();
            break;
        case '*' : 
            proizv();
             s=proizv();
            break;
        case '^' : 
            degree();
            s=degree();
            break;
        case '!' : 
            fact();
             s=fact();
            break;
        default : 
            printf("Error! No such action!"); 
            break;
    }
    
    
    printf("%0.f",s);
    getch();
    
    return 0;
    
}
float sum()
{   float rez;
    float a;
    float b;
    a=b=0;
    printf("BBedute 2 4ucJIan");
    scanf("%f %f",&a,&b);
    rez=a+b;
    return rez;
}
 
float razn()
{   float rez;
    float a;
    float b;
    
    printf("BBedute 2 4ucJIan");
    scanf("%f %f",&a,&b);
    rez=a-b;
    return rez;
}
float del()
{   float rez;
    float a;
    float b;
    
    printf("BBedute 2 4ucJIan");
    scanf("%f %f",&a,&b);
    rez=a/b;
    return rez;
 
}
 
float proizv()
{   float rez;
    float a;
    float b;
 
    
    printf("BBedute 2 4ucJIan");
    scanf("%f %f",&a,&b);
    rez=a*b;
    return rez;
 
}
 
 
 
float degree()
{
    float rez,a,b;
    
    printf("BBedute 4ucJIo u cteIIeHbn");
    scanf("%f %f",&a,&b);
    
    rez=pow(a,b);
    
    return rez;
}
 
float fact()
{   float a,b;
    float rez=1;
    int i=0;
    printf("BBedute 4ucJIon");
    scanf("%f",&a);
    for (i=1; i=<a; i++)
        rez=rez*i;
    return rez;
}

error C2059: синтаксическая ошибка: <
error C2143: синтаксическая ошибка: отсутствие «;» перед «)»
error C2143: синтаксическая ошибка: отсутствие «;» перед «)»

0

Каратель

Эксперт С++

6606 / 4025 / 401

Регистрация: 26.03.2010

Сообщений: 9,273

Записей в блоге: 1

24.02.2013, 15:15

5

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

Есть еще вопрос, не пойму где ошибки(

компилятор же пишет в какой строке ошибка

0

17 / 17 / 8

Регистрация: 18.09.2012

Сообщений: 184

24.02.2013, 15:24

 [ТС]

6

Jupiter, 1>c:usersкомпdocumentsvisual studio 2010projects333.cpp(126): error C2059: синтаксическая ошибка: <
где тут написана строка?

Добавлено через 1 минуту
Догадываюсь что (126)

Добавлено через 2 минуты
а нет..

Добавлено через 2 минуты
Все разобрался!

0

KostyaKulakov

Заблокирован

24.02.2013, 15:26

7

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include <iostream>
#include <stdio.h>
#include <conio.h>
 
 
float sum();
float razn();
float del();
float proizv();
float degree();
float fact();
 
 
int main()
{   
    
    int x,c;
    float s;
    printf("Bb|bepute deu`ctBue");
    scanf("%d",&c);
    switch(c)
    {
        case '+' : 
            sum(); 
            s=sum();
            break;
        case '-' : 
            razn();
            s=razn();
            break;
        case '/' : 
            del();
            s=fact();
            break;
        case '*' : 
            proizv();
             s=proizv();
            break;
        case '^' : 
            degree();
            s=degree();
            break;
        case '!' : 
            fact();
             s=fact();
            break;
        default : 
            printf("Error! No such action!"); 
            break;
    }
    
    
    printf("%0.f",s);
    getch();
    
    return 0;
    
}
float sum()
{   float rez;
    float a;
    float b;
    a=b=0;
    printf("BBedute 2 4ucJIan");
    scanf("%f %f",&a,&b);
    rez=a+b;
    return rez;
}
 
float razn()
{   float rez;
    float a;
    float b;
    
    printf("BBedute 2 4ucJIan");
    scanf("%f %f",&a,&b);
    rez=a-b;
    return rez;
}
float del()
{   float rez;
    float a;
    float b;
    
    printf("BBedute 2 4ucJIan");
    scanf("%f %f",&a,&b);
    rez=a/b;
    return rez;
 
}
 
float proizv()
{   float rez;
    float a;
    float b;
 
    
    printf("BBedute 2 4ucJIan");
    scanf("%f %f",&a,&b);
    rez=a*b;
    return rez;
 
}
 
 
 
float degree()
{
    float rez,a,b;
    
    printf("BBedute 4ucJIo u cteIIeHbn");
    scanf("%f %f",&a,&b);
    
    rez=pow(a,b);
    
    return rez;
}
 
float fact()
{   float a,b;
    float rez=1;
    int i=0;
    printf("BBedute 4ucJIon");
    scanf("%f",&a);
    for (i=1; i <= a; ++i)
        rez*=i;
    return rez;
}

0

knf

17 / 17 / 8

Регистрация: 18.09.2012

Сообщений: 184

24.02.2013, 16:37

 [ТС]

8

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

C++
1
for (i=1; i <= a; ++i)

Вот где

Добавлено через 48 минут
Опять вопрос по этому же коду.
Функция sum полностью для вещественных чисел, она и складывает вещественные и возвращает вещественное.
Вот я запускаю, ввожу +, ввожу 4.2 3.8 и он мне снова введите два числа..

Добавлено через 9 минут
Опять нашел)

0

IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

24.02.2013, 16:37

Помогаю со студенческими работами здесь

Синтаксическая ошибка!))
Вот код:
====================================================================
#include &lt;iostream&gt;…

Синтаксическая ошибка
Здраствуйте. Помогите, пожайлуста, выявить синтаксическую ошибку в коде:

#include &lt;fstream&gt;…

Синтаксическая ошибка
Ошибка 4 error C2065: Y: необъявленный идентификатор C:UsersstudentDesktopЯзыки…

синтаксическая ошибка
#include &lt;iostream&gt;
#include &lt;stdio.h&gt;
#include &lt;io.h&gt;
#include &lt;ctime&gt;

using namespace std;…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

8

Software errors are prevalent. It’s easy to make them, and it’s hard to find them. In this chapter, we’ll explore topics related to the finding and removal of bugs within our C++ programs, including learning how sto use the integrated debugger that is part of our IDE.

Although debugging tools and techniques aren’t part of the C++ standard, learning to find and remove bugs in the programs you write is an extremely important part of being a successful programmer. Therefore, we’ll spend a bit of time covering such topics, so that as the programs you write become more complex, your ability to diagnose and remedy issues advances at a similar pace.

If you have experience from debugging programs in another compiled programming language, much of this will be familiar to you.

Syntax and semantic errors

Programming can be challenging, and C++ is somewhat of a quirky language. Put those two together, and there are a lot of ways to make mistakes. Errors generally fall into one of two categories: syntax errors, and semantic errors (logic errors).

A syntax error occurs when you write a statement that is not valid according to the grammar of the C++ language. This includes errors such as missing semicolons, using undeclared variables, mismatched parentheses or braces, etc… For example, the following program contains quite a few syntax errors:

#include <iostream>

int main()
{
    std::cout < "Hi there"; << x << 'n'; // invalid operator (<), extraneous semicolon, undeclared variable (x)
    return 0 // missing semicolon at end of statement
}

Fortunately, the compiler will generally catch syntax errors and generate warnings or errors, so you easily identify and fix the problem. Then it’s just a matter of compiling again until you get rid of all the errors.

Once your program is compiling correctly, getting it to actually produce the result(s) you want can be tricky. A semantic error occurs when a statement is syntactically valid, but does not do what the programmer intended.

Sometimes these will cause your program to crash, such as in the case of division by zero:

#include <iostream>

int main()
{
    int a { 10 };
    int b { 0 };
    std::cout << a << " / " << b << " = " << a / b << 'n'; // division by 0 is undefined
    return 0;
}

More often these will just produce the wrong value or behavior:

#include <iostream>

int main()
{
    int x;
    std::cout << x << 'n'; // Use of uninitialized variable leads to undefined result

    return 0;
}

or

#include <iostream>

int add(int x, int y)
{
    return x - y; // function is supposed to add, but it doesn't
}

int main()
{
    std::cout << add(5, 3) << 'n'; // should produce 8, but produces 2

    return 0;
}

or

#include <iostream>

int main()
{
    return 0; // function returns here

    std::cout << "Hello, world!n"; // so this never executes
}

Modern compilers have been getting better at detecting certain types of common semantic errors (e.g. use of an uninitialized variable). However, in most cases, the compiler will not be able to catch most of these types of problems, because the compiler is designed to enforce grammar, not intent.

In the above example, the errors are fairly easy to spot. But in most non-trivial programs, semantic errors are not easy to find by eyeballing the code. This is where debugging techniques can come in handy.

Добавлено 16 апреля 2021 в 20:18

В программном обеспечении распространены ошибки. Их легко сделать, а найти сложно. В этой главе мы рассмотрим темы, связанные с поиском и устранением ошибок в наших программах на C++, включая изучение того, как использовать интегрированный отладчик, который является частью нашей IDE.

Хотя инструменты и методы отладки не входят в стандарт C++, умение находить и устранять ошибки в программах, которые вы пишете, является чрезвычайно важной частью успешной работы программиста. Поэтому мы уделим немного времени рассмотрению этих тем, чтобы по мере усложнения программ, которые вы пишете, ваша способность диагностировать и устранять проблемы развивалась с той же скоростью.

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

Синтаксические и семантические ошибки

Программирование может быть сложной задачей, и C++ – довольно необычный язык. Сложите эти две вещи вместе и получите множество способов сделать ошибку. Ошибки обычно делятся на две категории: синтаксические ошибки и семантические ошибки (логические ошибки).

Синтаксическая ошибка возникает, когда вы пишете инструкцию, недопустимую в соответствии с грамматикой языка C++. Сюда входят такие ошибки, как отсутствие точек с запятой, использование необъявленных переменных, несоответствие круглых или фигурных скобок и т.д. Например, следующая программа содержит довольно много синтаксических ошибок:

#include <iostream>
 
int main()
{
    std::cout < "Hi there"; << x; // недопустимый оператор (<), лишняя точка с запятой, необъявленная переменная (x)
    return 0 // отсутствие точки с запятой в конце инструкции
}

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

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

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

#include <iostream>
 
int main()
{
    int a { 10 };
    int b { 0 };
    std::cout << a << " / " << b << " = " << a / b; // деление на 0 не определено
    return 0;
}

Чаще всего они просто приводят к неправильному значению или поведению:

#include <iostream>
 
int main()
{
    int x;
    std::cout << x; // Использование неинициализированной переменной приводит к неопределенному результату
 
    return 0;
}

или же

#include <iostream>
 
int add(int x, int y)
{
    return x - y; // функция должна складывать, но это не так
}
 
int main()
{
    std::cout << add(5, 3); // должен выдать 8, но выдаст 2
 
    return 0;
}

или же

#include <iostream>
 
int main()
{
    return 0; // функция завершается здесь
 
    std::cout << "Hello, world!"; // поэтому это никогда не выполняется
}

Современные компиляторы стали лучше обнаруживать определенные типы распространенных семантических ошибок (например, использование неинициализированной переменной). Однако в большинстве случаев компилятор не сможет отловить большинство из этих типов проблем, потому что компилятор предназначен для обеспечения соблюдения грамматики, а не намерений.

В приведенных выше примерах ошибки довольно легко обнаружить. Но в большинстве нетривиальных программ, взглянув на код, семантические ошибки найти нелегко. Здесь могут пригодиться методы отладки.

Теги

C++ / CppDebugLearnCppДля начинающихОбучениеОтладкаПрограммирование

I’m working on this project and I’m REALLY close, I’m just gettin a C2059 error and I have no idea why?

#include <iostream>
using namespace std;

int main()
{
int guess;
int die;
float total = 10;
char ans;
cout << "Welcome to Dice Roll!" << endl;
cout << "Your bank total is: $" << total << ".00" << endl;
cout << "nGuess the next roll! It costs $1.00 to play!" << endl;
cout << "The correct guess nets you $100.00!n" << endl;
cin >> guess;

do
{
--total;
die = (int)(rand() % 6) + 1;
	
	if(guess < 1 || guess > 6)
	{
		cout << "Invalid Input" << endl;
		cout << "Try again? (Type 'Y' or 'N')" << endl;
		cin >> ans;
	}
	if(guess == die)
	{ 
		cout << "Congratulations! The dice rolled a" << die <<  "You won $100.00!" << endl;
		cout << "nYour bank total is: $" << total + 100 << ".00" << endl;
		cout << "Try again? (Type 'Y' or 'N')" << endl;
		cin >> ans;
	}
	if (guess != die)
	{
		cout << "I'm sorry, but you lost and we now have your dollar." << endl;
		cout << "nYour bank total is: $" << total << ".00" << endl;
		cout << "Try again? (Type 'Y' or 'N')" << endl;
		cin >> ans;
	} while(ans == 'Y' || 'y');

	
	if (ans != 'Y' || ans != 'y' || ans != 'N' || ans != 'n')
	{
		cout << "Invalid Input" << endl;
	}
	else
	{
	cout << "Thanks for playing! Your bank is $" << total << ".00" << endl;
	}
	}
return 0;
}
1>Compiling...
1>Lab9.cpp
1>c:usersstephon.stephon-pcdocumentsvisual studio 2008projectslab9lab9lab9.cpp(51) : error C2059: syntax error : 'return'

  • Синтаксическая ошибка missing operator semicolon or near draw
  • Синтаксис формулы если ошибка
  • Синтаксическая ошибка basic переменная sid уже определена
  • Синтаксико стилистические ошибки это
  • Синтаксико стилистические ошибки примеры