Ошибка void main void

Странные дела начинаются с short getX (Vector *v, int pos) — почему, если у вас вектор double, вы возвращаете short, а не double?

Аналогично, если у вас

double sum=0;
...
return sqrtf(sum);

и функция возвращает double, зачем же вычислять sqrtf, а не sqrt?…

void main()

неверно, нужен

int main()

Непонятно также

if (N==0) ;

И что вы хотите этим сказать? Кстати, на скриншоте у вас int main() и return после if (N==0), а вот это уже проблема: раз main возвращает int, то и return должен быть со значением, return 0;, например.

Вот все, что найдено компилятором. Правильно ли ваш код работает, а не компилируется — вопрос другой, не смотрел… Но даже навскидку:

void setN (Vector *v, int nr){
    if (nr<1) v->n=1;
    else v->n=nr;
}

Как я понимаю, это изменение размера (количества элементов) в векторе? Тогда почему вы не меняете выделенную память? А то ведь запросто может быть, что вы выделили 5 элементов, а потом сделали n сотней, и здравствуй, выход за пределы массива…

gylayko

30 / 29 / 15

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

Сообщений: 449

1

05.02.2012, 12:49. Показов 9867. Ответов 29

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


Студворк — интернет-сервис помощи студентам

Вот код программы, между void и main выдает ошибку declaration syntax error, что я не так делаю? моя первая прога на с++, поэтому прошу помощи)

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  #include<math.h>
  #include<stdio.h>
  #include<conio.h>
float x,y,a,b,z
 
   void main()
{
   clrscr();
   printf("Vvedite a:");
   scanf("%d";&a);
   printf("Vvedite b:");
   scanf("%d";&b);
   printf("Vvedite x:");
   scanf("%d";&x);
   y=0.02;
   z=((sin(2*x-b*b)-7*a*(y*y))/(x*x*x*x+1))-(sqrt(cos(y)-5*(exp(ln(y)*6)))/(6-cos(y));
   printf("z=%d",z);
   getch();
}



0



Эксперт С++

5054 / 3115 / 271

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

Сообщений: 7,045

05.02.2012, 12:54

2

gylayko, по стандарту функция main должа возвращать значение типа int.



0



Полярный

476 / 448 / 158

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

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

05.02.2012, 12:56

3

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

float x,y,a,b,z

semicolon ; забыли

silent_1991,

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

#include<math.h>
\…

getch();

Видимо в борланде работает -> на void ему пофиг.
А так лучше конечно на int поправить



0



silent_1991

05.02.2012, 12:57

Не по теме:

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

semicolon ; забыли

А вот на это даже не смотрел))



0



BumerangSP

4299 / 1421 / 463

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

Сообщений: 2,939

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

05.02.2012, 13:01

5

И на это вот:

C
1
2
3
4
5
scanf("%d";&a);
   printf("Vvedite b:");
   scanf("%d";&b);
   printf("Vvedite x:");
   scanf("%d";&x);



0



Эксперт С++

5054 / 3115 / 271

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

Сообщений: 7,045

05.02.2012, 13:03

6

dimcoder, расширение не выдаёт борланд, ибо это Pure C (правда, насколько он Pure в борланде, я не знаю). А вот clrscr(); выдаёт.



0



30 / 29 / 15

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

Сообщений: 449

05.02.2012, 13:04

 [ТС]

7

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

gylayko, по стандарту функция main должа возвращать значение типа int.

а у меня возвращает типа float, а что тогда нужно вместо void main() ? при замене переенных на тип int ошибка не пропадает)



0



silent_1991

Эксперт С++

5054 / 3115 / 271

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

Сообщений: 7,045

05.02.2012, 13:06

8

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

а у меня возвращает типа float

ЩИТО?

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

при замене переенных на тип int

А переменный тут при чём? По стандарту функция main может быть описана либо как

C
1
int main(void);

, либо как

C
1
int main(int argc, char *argv[]);



0



BumerangSP

4299 / 1421 / 463

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

Сообщений: 2,939

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

05.02.2012, 13:09

9

Так должно работать:

C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  #include<math.h>
  #include<stdio.h>
  #include<conio.h>
float x,y,a,b,z;
 
   int main()
{
   printf("Vvedite a:");
   scanf("%d",&a);
   printf("Vvedite b:");
   scanf("%d",&b);
   printf("Vvedite x:");
   scanf("%d",&x);
   y=0.02;
   z=((sin(2*x-b*b)-7*a*(y*y))/(x*x*x*x+1))-(sqrt(cos(y)-5*(exp(log(y)*6)))/(6-cos(y)));
   printf("z=%d",z);
   getch();
   return 0;
}



0



gylayko

30 / 29 / 15

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

Сообщений: 449

05.02.2012, 13:12

 [ТС]

10

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

Так должно работать:

C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  #include<math.h>
  #include<stdio.h>
  #include<conio.h>
float x,y,a,b,z;
 
   int main()
{
   printf("Vvedite a:");
   scanf("%d",&a);
   printf("Vvedite b:");
   scanf("%d",&b);
   printf("Vvedite x:");
   scanf("%d",&x);
   y=0.02;
   z=((sin(2*x-b*b)-7*a*(y*y))/(x*x*x*x+1))-(sqrt(cos(y)-5*(exp(log(y)*6)))/(6-cos(y)));
   printf("z=%d",z);
   getch();
   return 0;
}

все равно перед main та же ошибка!



0



silent_1991

Эксперт С++

5054 / 3115 / 271

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

Сообщений: 7,045

05.02.2012, 13:15

11

А вот так будет даже правильно работать. И будет выглядеть более-менее верно с точки зрения стиля.

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
#include<math.h>
#include<stdio.h>
#include<conio.h>
 
int main(void)
{
    float x, y, a, b, z;
    
    printf("Vvedite a:");
    scanf("%f", &a);
    printf("Vvedite b:");
    scanf("%f", &b);
    printf("Vvedite x:");
    scanf("%f", &x);
    
    y = 0.02;
    z = ((sin(2 * x - b * b) - 7 * a * (y * y)) / (x * x * x * x + 1)) - (sqrt(cos(y) - 5 * (exp(log(y) * 6))) / (6 - cos(y)));
    
    printf("z=%f", z);
    
    getch();
    
    return 0;
}



0



Полярный

476 / 448 / 158

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

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

05.02.2012, 13:16

12

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

все равно перед main та же ошибка!

Среду разработки и компилер назовите. Скомпилел на борланд 3.1 все работает.



0



BumerangSP

4299 / 1421 / 463

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

Сообщений: 2,939

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

05.02.2012, 13:17

13

C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  #include<math.h>
  #include<stdio.h>
float x,y,a,b,z;
   int main()
{
   printf("Vvedite a:");
   scanf("%f",&a);
   printf("Vvedite b:");
   scanf("%f",&b);
   printf("Vvedite x:");
   scanf("%f",&x);
   y=0.02;
   z=((sin(2*x-b*b)-7*a*(y*y))/(x*x*x*x+1))-(sqrt(cos(y)-5*(exp(log(y)*6)))/(6-cos(y)));
   printf("z=%f",z);
   return 0;
}

http://liveworkspace.org/code/… c9afa745ce
Как бы не думал, что он ошибку выдаст. Максимум предупреждение



1



gylayko

30 / 29 / 15

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

Сообщений: 449

05.02.2012, 13:25

 [ТС]

14

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

Среду разработки и компилер назовите. Скомпилел на борланд 3.1 все работает.

тот же борланд 3.1 только через dosbox ибо 64 бит!

Добавлено через 57 секунд

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

C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  #include<math.h>
  #include<stdio.h>
float x,y,a,b,z;
   int main()
{
   printf("Vvedite a:");
   scanf("%f",&a);
   printf("Vvedite b:");
   scanf("%f",&b);
   printf("Vvedite x:");
   scanf("%f",&x);
   y=0.02;
   z=((sin(2*x-b*b)-7*a*(y*y))/(x*x*x*x+1))-(sqrt(cos(y)-5*(exp(log(y)*6)))/(6-cos(y)));
   printf("z=%f",z);
   return 0;
}

http://liveworkspace.org/code/… c9afa745ce
Как бы не думал, что он ошибку выдаст. Максимум предупреждение

а что за программа на фото? так ведь удобнее! без всяких досбоксов и т.д. работает?



0



4299 / 1421 / 463

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

Сообщений: 2,939

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

05.02.2012, 13:26

15

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

а что это за программа на фото?

Если Вы о ссылке, то это онлайн компилер. Кстати, вещь удобная)



0



30 / 29 / 15

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

Сообщений: 449

05.02.2012, 13:29

 [ТС]

16

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

Если Вы о ссылке, то это онлайн компилер. Кстати, вещь удобная)

ну да, там все работает также как и у Вас! а через обычный компилятор борланд 3.1 нифига!



0



Эксперт С++

5054 / 3115 / 271

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

Сообщений: 7,045

05.02.2012, 13:32

17

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

обычный компилятор борланд 3.1

А потому что это не обычный компилятор. Это чрезвычайно древний компилятор, ему уже 20 лет. за это время успели выпустить три стандарта и несколько правок к ним.



0



4299 / 1421 / 463

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

Сообщений: 2,939

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

05.02.2012, 13:34

18

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

ну да, там все работает также как и у Вас! а через обычный компилятор борланд 3.1 нифига!

Это говорит о том, что код правильный. Но в онлайн компиляторе можно только проверять на ошибки. Поэтому стоит найти лучше что-нибудь поновей борланда, типа dev-cpp. Лучше конечно сразу MVC.



0



Эксперт С++

5054 / 3115 / 271

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

Сообщений: 7,045

05.02.2012, 13:36

19

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

MVC

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

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

dev-cpp

Не такая уж она и новая.

gylayko, советую среду, к которой можно подключить любой компилятор (на ваш выбор) и компилятор mingw, как можно новее (последняя релизная версия 4.6.2).



0



4299 / 1421 / 463

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

Сообщений: 2,939

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

05.02.2012, 13:40

20

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

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

По крайней мере уж с такими ошибками должен справляться

Слышал, что WxDev-cpp вроде как обновляется.



0



  • Forum
  • Beginners
  • void main problem

void main problem

i am trying to use this given tutorial and main needs to be void for future tutorials, but every time i compile it as void, it gives an error saying main must return an int. Although on the tutorial it worked.
I know math.h and string do not need to be there, but it is for future purposes.

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
#include <iostream>
#include <math.h>
#include <string>
using namespace std;


void main()
{
    int people;
    float bill, tip, totaltip, total;

    cout << "How much is the bill? ";
    cin >> bill;
    cout <<"How many people will be splitting the bill? ";
    cin >> people;
    cout << "What is the percetage of the tip? ";
    cin >> tip;

    totaltip = bill *(tip/100.);
    total = (totaltip + bill) /people;

    cout << "The total tip at %" << tip << " is $" << totaltip << '.' << endl;
    cout << "Each person will pay $" << total << '.' << endl;
   
}

Last edited on

metulburr wrote:
main must return an int

Last edited on

though it works on other peoples tutorials?

I would probably find a different tutorial…

The standard says main must return an int, but apparently some compilers will let you get away with void. I just tested with msvc 2010, and it will compile

without warning.

yeah dude, main() most definitely returns an int. Consider this simple boilerplate code:
int main(int nArgs, char* pszArgs)

its kinda just what i was told to impliment in all my main methods and i would be safe

Topic archived. No new replies allowed.

Looks like no one’s replied in a while. To start the conversation again, simply

ask a new question.

Hey there. I’ve just started taking a object-oriented C++ course online — it’s been a few years since I’ve programmed C++, although I’ve programmed C more recently. Anyways, they expect me to use Visual Studio as my compiler, but I’m not budging — Xcode is where I like to write my code, and I don’t feel like reinstalling Parallels. The problem is, the code I’m supposed to use for one of the exercises defines main() using ‘void’ instead of ‘int’. In my experience programming C (and C++ if I’m not mistaking), this has never been a problem. However, with Xcode I’m getting an error that says, «error: ‘::main’ must return ‘int'». Can anyone toss me some insight into why I’m getting this error, and how I may be able to correct it so that the compiler accepts main() as ‘void’? I’ve checked the project settings under «GCC 4.0 — Language», but I didn’t find anything I could recognize as relevant, other than «C Language Dialect» being set to C99, and I don’t think that’s the issue.

Any help is appreciated — thanks.

MacBook,

Mac OS X (10.5.8)

Posted on Sep 5, 2010 4:21 AM

Tron55555 wrote:

So I guess there’s no easy way around that then?

The easy answer is to use int. Like a number of things in the Windows world, «void main()» is flat-out syntactically invalid. The Microsoft Foundation Class library will not compile with a standards-compliant C++ compiler — because it isn’t valid C++. Microsoft’s compilers have switches to enable standards compliance, but you should never use them. GCC has switches to enable it to compile MFC, but no one ever uses them.

Apple gets a lot of press with the iPad and iPhone, but the reality is that Macs are still a distant minority in any corporate/educational environment. University professors, including those in Computer Science, are known for living 20 years in the past.

You are going to have to do what every Mac user in a computer science class has always done, write your code on your Mac because you love the Mac, then port it to Windows or whatever else. You are going to need Parallels for this course. The end result is that your code will be better than anyone else’s in the class. You have to write code good enough to satisfy two compilers and you will be a better programmer for it.

Posted on Sep 6, 2010 6:24 AM

error with ‘void main()’ in C++ tool

error: ‘::main’ must return ‘int’

#include <iostream>

using namespace std;

int i=1;
void main()
{
    int i=i;
}

There was an error running:

error: '::main' must return 'int'

Reason: The C language standard allows the main function to be of type void. According to the C++ standard, main must be of type int.

Intelligent Recommendation

Main() error report-crazy delivery (not) return

Main’s error report-crazy delivery (not) return main() error Change the number of parameters Change parameter type But after all About the call stack Linux View Adjustment Windows View Adjustment (Com…

int main() void main()

Write a directory title here C/C++ :void main() C C++ void main int main( int argc, char *argv[], char *envp[] ) ? C/C++ :void main() void main(), , C , , void main(), int main() ? ? ? , C Primer Plus…

More Recommendation

error C4716 must return a value. Processing

problem The following error was reported, but I couldn’t find how to solve it. Record it here. error C4716: «TApamaInterface::GetEventValue»: Must return a value error C4716: «TApamaInt…

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • Ошибка vmware workstation intel vt x
  • Ошибка vmware timeout efi network
  • Ошибка vk api мои гости
  • Ошибка vitashell this feature

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии