Misplaced else c ошибка

I cannot seem to fix the «misplaced else» error in the code below. This code should collect and compute for term grades and give remarks depending on the score.

#include <conio.h>
#include <stdio.h>

main()
{
    char name[20];
    int exam, q1, q2, q3, ass, sw, att, avgq, CS, TG;
    clrscr();
    printf("Name: ");
    gets(name);
    printf("nExam: ");
    scanf("%d", &exam);
    printf("nQuiz #1: ");
    scanf("%d", &q1);
    printf("nQuiz #2: );
    scanf("%d", &q2);
    printf("nQuiz #3: ");
    scanf("%d", &q3);
    printf("nAssignment: ");
    scanf("%d", &ass);
    printf("nSeatwotk: ");
    scanf("%d", &sw);
    printf("nAttendance: ");
    scanf("%d", &att);
    CS = (0.4*ass) + (0.4*sw) + (0.2*att);  // class standing //
    avgq = (q1 + q2 + q3)/3;  // Average quiz //
    TG = (0.4*exam) + (0.3*avgq) + (0.3*CS);  // Term grade //
    if(TG >= 90)
       printf("Term Grade: %d", TG);
       printf("Remarks: EXCELLENT");
    else if (TG>=80 && TG<=89)
       printf("Term Grade: %d", TG);
       printf("Remarks: SATISFACTORY");
    else if (TG>=76 && TG<=79)
       printf("Term Grade: %d", TG);
       printf("Remarks: GOOD");
    else if (TG == 75)
       printf("Term Grade: %d", TG);
       printf("Remarks: PASSING");
    else if (TG<74)
       printf("Term Grade: %d", TG);
       printf("Remarks: FAILED");
    else
       printf("Invalid Input.  Try again");
    getch();
    return 0;
}

mordol

1 / 1 / 2

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

Сообщений: 313

1

16.09.2016, 20:18. Показов 3427. Ответов 1

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


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

C++
1
2
3
4
5
6
7
8
if (Edit1->Text == "admin" && Edit2->Text == "123456789")
          Form2->Show();
 else if (Edit1->Text == "admin" && Edit2->Text == "123456789")
          Form2->Show();
          Form2->Image2->Visible = false;
          Form2->Image3->Visible = false;
          else
         ShowMessage("Данные введены неверно");

Ругается на else:Misplaced else
Подскажите пожалуйста в чем ошибка



0



gunslinger

случайный прохожий

2442 / 1655 / 557

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

Сообщений: 4,640

16.09.2016, 20:37

2

C++
1
2
3
4
5
6
7
8
9
10
if (Edit1->Text == "admin" && Edit2->Text == "123456789")
          Form2->Show();
 else if (Edit1->Text == "admin" && Edit2->Text == "123456789")
         {
          Form2->Show();
          Form2->Image2->Visible = false;
          Form2->Image3->Visible = false;
         }
          else
         ShowMessage("Данные введены неверно");



0



Нуб здесь. Я не могу исправить ошибку «неуместное другое» в приведенном ниже коде. Этот код должен собирать и вычислять оценку за семестр и давать замечания в зависимости от оценки. Любая помощь приветствуется.

#include <conio.h>
#include <stdio.h>
main()
{
char name[20];
int exam, q1, q2, q3, ass, sw, att, avgq, CS, TG;
clrscr();
printf("Name: ");
gets(name);
printf("nExam: ");
scanf("%d", &exam);
printf("nQuiz #1: ");
scanf("%d", &q1);
printf("nQuiz #2: );
scanf("%d",&q2);
printf("nQuiz #3: ");
scanf("%d",&q3);
printf("nAssignment: ");
scanf("%d",&ass);
printf("nSeatwotk: ");
scanf("%d",&sw);
printf("nAttendance: ");
scanf("%d",&att);
CS=(0.4*ass)+(0.4*sw)+(0.2*att);  //class standing//
avgq=(q1+q2+q3)/3;  //average quiz//
TG=(0.4*exam)+(0.3*avgq)+(0.3*CS);  //term grade//
if(TG>=90)
printf("Term Grade: %d",TG);
printf("Remarks: EXCELLENT");
else if (TG>=80 && TG<=89)
printf("Term Grade: %d",TG);
printf("Remarks: SATISFACTORY");
else if (TG>=76 && TG<=79)
printf("Term Grade: %d",TG);
printf("Remarks: GOOD");
else if (TG==75)
printf("Term Grade: %d",TG);
printf("Remarks: PASSING");
else if (TG<74)
printf("Term Grade: %d",TG);
printf("Remarks: FAILED");
else
printf("Invalid Input.  Try again");
getch();
return 0;
}

-2

Решение

э-э-э! нуб оповещение! шучу, нам всем надо с чего-то начинать;)

так что не волнуйтесь, прекрасная дева! проблема лежит здесь:

когда вы объявляете оператор if, вы должны заключить тело оператора if в фигурные скобки. Если вы этого не сделаете, будет запущена только первая строка под оператором if. Вот пример:

// here, both do something 1 and do something 2 are being run in the if statement
if (something) {
do something 1;
do something 2;
}

// here, only do something 1 will get run inside the if statement
if (something)
do something 1;
do something 2;

Итак, вернемся к вашей проблеме. Вы должен поместите фигурные скобки {} вокруг кода в операторе if, если тело оператора if состоит из более чем 1 строки.

if (something)
do something 1;
do something 2;
else
do something 3;

эквивалентно

if (something)
do something 1;
do something 2;
else do something 3;

Вот почему вы еще оператор выдает ошибку. Каждый должен иметь перед собой if.

1

Другие решения

C ++ не использует отступы для определения концов операторов. Вам нужны фигурные скобки, если вы хотите более одного утверждения.

Вместо:

if (a)
b;
c;
else
d;

Использование:

if (a) {
b;
c;
} else {
d;
}

0

Если у вас есть более 1 строки под if или else, они должны быть заключены в фигурные скобки, например так:

if(TG>=90)
{
printf("Term Grade: %d",TG);
printf("Remarks: EXCELLENT");
}
else if (TG>=80 && TG<=89)
{
printf("Term Grade: %d",TG);
printf("Remarks: SATISFACTORY");
}

0

  1. 04-25-2010


    #1

    rollyah is offline


    Registered User


    Angry Misplaced else in function main — help?

    Hello,

    i’m a newbie with C
    i started learning it like 2 weeks ago by getting a few ebooks that i’ve found online..

    attached with the ebook a booklet full of exercises to test what i’ve learned for each chapter but without the solutions .. :S

    i managed to get through most tests but im stuck at these two.. hope you could point out wht im doing wrong:

    Write a complete C program that asks the user to enter continuously a series of words and the
    word �end� to stop.
    For each word entered, you should output the number of characters of this word and then ask him
    to enter the other word.
    Finally, when he finished entering all the words, you should output the number of words entered
    (excluding �end�)

    Code:

    #include <stdio.h>
    int main(void)
    {
    char word[256];
    char stop[3]="end";
    int cnt=0;
    printf("Enter a word to know it's number of characters. once finished enter "end" to stopn");
    scanf("%s",&word);
    while (stop!=word)
    printf("The number of characters of %s is %un",word,strlen(word));
    cnt = cnt++;
    else
    printf("you've decided to stop. you entered %d words so far.n",cnt);
    return 0;	
    }

    and this is the error:

    Borland C++ 5.5.1 for Win32 Copyright (c) 1993, 2000 Borland
    tma.c:
    Warning W8065 tma.c 10: Call to function ‘strlen’ with no prototype in function main
    Error E2054 tma.c 11: Misplaced else in function main
    *** 1 errors in Compile ***

    Write a complete C program that calculates the roots of any quadratic equation of the form ax2 +
    bx + c = 0 where a, b and c are variables that should be entered by user.
    First, if a = 0 then the root is x= -c/b
    otherwise, you have to find Δ, Δ=b2 � 4ac
    If Δ< 0 there are no roots
    If Δ= 0 we have 2 double roots: x1 = x2 = -b/2a
    If Δ>0, two roots x1 = (-b-√Δ)/2a and (�b +√Δ)/2a
    Hint: you can include math library to use some math functions

    Code:

    #include "stdio.h"
    #include "math.h"
    
    void main()
    {
    int a,b,c,delta;
    float x,x1;
    printf("n Enter values of a,b,c for finding roots of a quadratic eq:n");
    scanf("%d%d%d",&a,&b,&c);
    
    if (a == 0) {
    x = -c/b
    printf("in this case the root is %f",x);
    }
    else
     delta=b^2-4*a*c
    
    if ( delta<0)
    {
    printf("there are no roots")
    }
    if (delta == 0)
    {
    x= -b/(2*a);
    printf("we have double roots %f",x);
    }
    if (delta>0)
    { 
    x = (-b-sqrt(delta))/2*a)
    x1 = (-b+sqrt(delta)/2*a
    printf("we have two roots which are %f and %f",x,x1);
    }
    }

    ERROR:

    Borland C++ 5.5.1 for Win32 Copyright (c) 1993, 2000 Borland
    new.c:
    Error E2379 new.c 13: Statement missing ; in function main
    Error E2379 new.c 18: Statement missing ; in function main
    Warning W8004 new.c 33: ‘x’ is assigned a value that is never used in function main
    Warning W8004 new.c 33: ‘delta’ is assigned a value that is never used in function main
    *** 2 errors in Compile ***

    Last edited by rollyah; 04-25-2010 at 01:05 AM.

    Reason: added the 2nd error


  2. 04-25-2010


    #2

    laserlight is offline


    C++ Witch

    laserlight's Avatar


    The else must have a matching if, but there isn’t any. In fact, it looks like you don’t need an else.

    By the way, you should indent your code properly. If you do so, you may discover a logic error due to the lack of braces.

    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)

    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. «Finding the smallest program that demonstrates the error» is a powerful debugging tool.

    Look up a C++ Reference and learn How To Ask Questions The Smart Way


  3. 04-25-2010


    #3

    rollyah is offline


    Registered User


    Quote Originally Posted by laserlight
    View Post

    The else must have a matching if, but there isn’t any. In fact, it looks like you don’t need an else.

    By the way, you should indent your code properly. If you do so, you may discover a logic error due to the lack of braces.

    thanks for your reply

    but if i remove else wouldn’t that lead to an infinite loop?

    im struggling to learn the how Tos for C so thanks again for helping out


  4. 04-25-2010


    #4

    Elysia is offline


    C++まいる!Cをこわせ!


    Start by doing so… First, indent your code.
    Second, check all your lines of code for missing ; (there are at least two).
    Third, check all your lines for missing parenthesises (there is at least one).
    And fourth, there is a problem in the algorithm. a^2 is not a squared (it’s a XOR 2). Nor should there be any squared variables in the formula. Look at it again, closely.
    And last, you are missing parenthesises again. When you have a*b/c*d, you’ll have to add parenthesises, remember? This is like a calculator.
    And change void main to int main.

    Quote Originally Posted by Adak
    View Post

    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.

    Quote Originally Posted by Salem
    View Post

    You mean it’s included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.


  5. 04-25-2010


    #5

    nonpuz is offline


    Ultraviolence Connoisseur


    Also your stop[3] doesn’t leave room for a trailing null so it is actually an array of characters, not a valid C string.

    You should use char stop[] = «end»; this will include the trailing . This is important due to the next error (besides the ones mentioned above) that you are trying to compare a character array to a string using a simple ==.

    If you make end[] a string as I said above, then you can use strcmp(end,word) == 0 to see if they match.

    Of course you also need to include string.h for strcmp and strlen() which you are already using.


  6. 04-30-2010


    #6

    rollyah is offline


    Registered User


    so i found my prob with the first excercise..
    though i’m still facing issues with the 2nd..

    Code:

    #include <stdio.h>
    #include <math.h>
    int main (void)
    {
    int a,b,c;
    float x,x1,x2,y,delta;
         printf("enter three numbers pleasen");
    	 scanf("%d%d%d",a,b,c);
    	 delta=b*b-4*a*c;
    	     if (a==0)
    		     x=(-c/b);
    			 printf("the root is %fn",x);
    		 else 
    		     printf("Delta=b2-4ac is equal to %fn",delta);
    			 
    		    if (delta<0)
    			     printf("there are no rootsn");
    			else
    			    if (delta==0)
    			        y=(-b/(2*a));
    		            printf("we have double roots x1=x2=%d/2*%d=%fn",a,b,y);
    				else
    			        if (delta>0)
    			            x1=((-b+sqrt(delta))/(2*a));
    				        x2=((-b+sqrt(delta))/(2*a));
    				        printf("there are two roots which are %f and %fn",x1,x2);
    				 
    return 0;	     	 
    }

    error:

    Error E2054 roland2.c 13: Misplaced else in function main
    Error E2054 roland2.c 22: Misplaced else in function main
    *** 2 errors in Compile ***


  7. 04-30-2010


    #7

    Elysia is offline


    C++まいる!Cをこわせ!


    Fix your indentation.
    It’s your tool for finding these kinds of things.

    Quote Originally Posted by Adak
    View Post

    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.

    Quote Originally Posted by Salem
    View Post

    You mean it’s included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.


  8. 04-30-2010


    #8

    rollyah is offline


    Registered User


    Quote Originally Posted by Elysia
    View Post

    Fix your indentation.
    It’s your tool for finding these kinds of things.

    thank you for your advice.. but im struggling here..
    i tried fxing my indentation over and over again..
    i’m not sure i’m even doing it right..
    any advice?


  9. 04-30-2010


    #9

    Elysia is offline


    C++まいる!Cをこわせ!


    For example, Visual Studio has an indentation tool. There are others.
    But it isn’t difficult to do it yourself. Consider this indented code of yours. You should be able to spot the problem:

    Code:

    #include <stdio.h>
    #include <math.h>
    int main (void)
    {
    	int a,b,c;
    	float x,x1,x2,y,delta;
    	printf("enter three numbers pleasen");
    	scanf("%d%d%d",a,b,c);
    	delta=b*b-4*a*c;
    	if (a==0)
    		x=(-c/b);
    	printf("the root is %fn",x);
    	else 
    		printf("Delta=b2-4ac is equal to %fn",delta);
    
    	if (delta<0)
    		printf("there are no rootsn");
    	else
    		if (delta==0)
    			y=(-b/(2*a));
    	printf("we have double roots x1=x2=%d/2*%d=%fn",a,b,y);
    		else
    			if (delta>0)
    				x1=((-b+sqrt(delta))/(2*a));
    	x2=((-b+sqrt(delta))/(2*a));
    	printf("there are two roots which are %f and %fn",x1,x2);
    
    	return 0;	     	 
    }

    Quote Originally Posted by Adak
    View Post

    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.

    Quote Originally Posted by Salem
    View Post

    You mean it’s included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.


  10. 04-30-2010


    #10

    rollyah is offline


    Registered User


    Quote Originally Posted by Elysia
    View Post

    For example, Visual Studio has an indentation tool. There are others.
    But it isn’t difficult to do it yourself. Consider this indented code of yours. You should be able to spot the problem:

    Code:

    #include <stdio.h>
    #include <math.h>
    int main (void)
    {
    	int a,b,c;
    	float x,x1,x2,y,delta;
    	printf("enter three numbers pleasen");
    	scanf("%d%d%d",a,b,c);
    	delta=b*b-4*a*c;
    	if (a==0)
    		x=(-c/b);
    	printf("the root is %fn",x);
    	else 
    		printf("Delta=b2-4ac is equal to %fn",delta);
    
    	if (delta<0)
    		printf("there are no rootsn");
    	else
    		if (delta==0)
    			y=(-b/(2*a));
    	printf("we have double roots x1=x2=%d/2*%d=%fn",a,b,y);
    		else
    			if (delta>0)
    				x1=((-b+sqrt(delta))/(2*a));
    	x2=((-b+sqrt(delta))/(2*a));
    	printf("there are two roots which are %f and %fn",x1,x2);
    
    	return 0;	     	 
    }

    im using notepad
    and command line Borland C++ 5.5.1 for Win32 Copyright (c) 1993, 2000 Borland

    i downloaded «Microsoft Visual C++ 2008 Express Edition»
    though i’m ashamed to admit that i didn’t know how to use it..

    PS: thanks for your effort by indenting but i’m still not noticing the prob..
    i’m reading the notes ive taken from the net over and over again..
    im pretty sure there’s something im missing but im not finding it out..

    Last edited by rollyah; 04-30-2010 at 12:19 PM.


  11. 04-30-2010


    #11

    Elysia is offline


    C++まいる!Cをこわせ!


    Code:

    #include <stdio.h>
    #include <math.h>
    int main (void)
    {
    	int a,b,c;
    	float x,x1,x2,y,delta;
    	printf("enter three numbers pleasen");
    	scanf("%d%d%d",a,b,c);
    	delta=b*b-4*a*c;
    	if (a==0)
    		x=(-c/b);
    	printf("the root is %fn",x);
    	else 
    		printf("Delta=b2-4ac is equal to %fn",delta);
    
    	if (delta<0)
    		printf("there are no rootsn");
    	else
    		if (delta==0)
    			y=(-b/(2*a));
    	printf("we have double roots x1=x2=%d/2*%d=%fn",a,b,y);
    		else
    			if (delta>0)
    				x1=((-b+sqrt(delta))/(2*a));
    	x2=((-b+sqrt(delta))/(2*a));
    	printf("there are two roots which are %f and %fn",x1,x2);
    
    	return 0;	     	 
    }

    Problematic lines are in red.
    We see from the indentation that, for example, the printf lines do not belong to the IF statement. Braces are required if you want more than one statement in an if.
    As a result of this, the else does not directly follow the if, and therefore, the compiler cannot determine which if statement it belongs to and so it complains.
    There are many good tutorials on Visual Studio on the web.
    Even if you don’t use it, you shouldn’t use Notepad for creating code. Either use a real editor or an IDE.

    Quote Originally Posted by Adak
    View Post

    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.

    Quote Originally Posted by Salem
    View Post

    You mean it’s included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.


  12. 04-30-2010


    #12

    rollyah is offline


    Registered User


    Quote Originally Posted by Elysia
    View Post

    Code:

    #include <stdio.h>
    #include <math.h>
    int main (void)
    {
    	int a,b,c;
    	float x,x1,x2,y,delta;
    	printf("enter three numbers pleasen");
    	scanf("%d%d%d",a,b,c);
    	delta=b*b-4*a*c;
    	if (a==0)
    		x=(-c/b);
    	printf("the root is %fn",x);
    	else 
    		printf("Delta=b2-4ac is equal to %fn",delta);
    
    	if (delta<0)
    		printf("there are no rootsn");
    	else
    		if (delta==0)
    			y=(-b/(2*a));
    	printf("we have double roots x1=x2=%d/2*%d=%fn",a,b,y);
    		else
    			if (delta>0)
    				x1=((-b+sqrt(delta))/(2*a));
    	x2=((-b+sqrt(delta))/(2*a));
    	printf("there are two roots which are %f and %fn",x1,x2);
    
    	return 0;	     	 
    }

    Problematic lines are in red.
    We see from the indentation that, for example, the printf lines do not belong to the IF statement. Braces are required if you want more than one statement in an if.
    As a result of this, the else does not directly follow the if, and therefore, the compiler cannot determine which if statement it belongs to and so it complains.
    There are many good tutorials on Visual Studio on the web.
    Even if you don’t use it, you shouldn’t use Notepad for creating code. Either use a real editor or an IDE.

    ah that thts the prob..
    i checked all my notes i didnt have anything concerning «braces are required if theres more than a statement»
    thanks for the info..
    i’m gonna look into mroe tutorials online..
    PS: i were able to compile it but it’s crashing..
    any logical error that you can notice?
    don’t point it out i want to try and find it out on my own if possible..
    sorry for being pushy..


  13. 04-30-2010


    #13

    Elysia is offline


    C++まいる!Cをこわせ!


    All I can say is that it’s not a logic problem that causes your crash.
    I could elaborate on where and why, if you want, but seeing as you did state you want to find it yourself, you’ll have to make another reply if you want it.
    Take your time.

    Quote Originally Posted by Adak
    View Post

    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.

    Quote Originally Posted by Salem
    View Post

    You mean it’s included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.


  14. 04-30-2010


    #14

    rollyah is offline


    Registered User


    Quote Originally Posted by Elysia
    View Post

    All I can say is that it’s not a logic problem that causes your crash.
    I could elaborate on where and why, if you want, but seeing as you did state you want to find it yourself, you’ll have to make another reply if you want it.
    Take your time.

    i commented everything to be able to pinpoint the prob..

    Code:

    #include <stdio.h>
    //#include <math.h>
    int main (void)
    {
    	int a,b,c;
    	//float x,x1,x2,y,delta;
    	printf("enter your first number	pleasen");
    	scanf("%d",a);
    	printf("enter your second number pleasen");
    	scanf("%d",b);
    	printf("enter your third number	pleasen");
        scanf("%d",c);
    	printf("%d,%d,%d",a,b,c);
    	//delta=(b*(b-(4*a*c)));
    	//if (a==0)
    	    //{
    		//x=(-c/b);
    	    //printf("the root is %fn",x);
    		//}
    	
    	//else 
    		//printf("Delta=b2-4ac is equal to %fn",delta);
    
    	//if (delta<0)
    	//	printf("there are no rootsn");
    	//else
    	//if (delta==0)
    	//{
    	//		y=(-b/(2*a));
    	 //       printf("we have double roots x1=x2=%d/2*%d=%fn",a,b,y);
    //			}
    //	else
    //	if (delta>0)
    //			x1=((-b+sqrt(delta))/(2*a));
    //	        x2=((-b+sqrt(delta))/(2*a));
    //	printf("there are two roots which are %f and %fn",x1,x2);
    
    	return 0;	     	 
    }

    and it’s still crashing..
    what did i do wrong?


  15. 04-30-2010


    #15

    Elysia is offline


    C++まいる!Cをこわせ!


    scanf requires pointers to where it should store the input. You are merely passing the contents of the variables to scanf.
    Aside from that, you should probably be getting warnings in some form or another.

    Quote Originally Posted by Adak
    View Post

    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.

    Quote Originally Posted by Salem
    View Post

    You mean it’s included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.


>
Вопрос о массиве и StringGrid

  • Подписаться на тему
  • Сообщить другу
  • Скачать/распечатать тему



Сообщ.
#16

,
24.02.04, 05:19

    Цитата

    compaq, 23.02.04, 23:31
    Нет что то твой код не пашет апять вылетело окно Debugger Exception Notification и подсветило синим

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

    Цитата

    compaq, 23.02.04, 23:31
    Что это вообше такое Debugger Exception Notification

    Это уведомление о том, что произошло исключение при выполнении под отладчиком.

    Цитата

    compaq, 23.02.04, 23:31
    И ещё а как будет выглядить код на запись массива в StringGrid

    Примерно так:

    ExpandedWrap disabled

      int i;

      double results[29];

      for( i=0 ; i < 29 ; i++ ) {

         try{

            StringGrid1->Cells[1][i] = AnsiString(results[i]);

         } catch( … ) {

         }

      }


    ZEE



    Сообщ.
    #17

    ,
    24.02.04, 07:39

      2compaq — вероятно у тебя в Cells не числовые значения — а т.к. ты наверняка запускаешь прогу прям из Билдера — то не зависимо от try-catch срабатывает тот самый Debugger Exception Notification.
      Попробуй или заполнить таблицу числовыми значениями до нажатия заветной кнопки, или запуская прогу отдельно — после компиляции.

      Добавлено в 24.02.04, 07:40:
      а, ну вот не заметил что trainer почти тоже самое написал…

      Wizard

      Bas



      Сообщ.
      #18

      ,
      24.02.04, 07:56

        ExpandedWrap disabled

          Values[i] = StrToFloat(StringGrid1->Cells[1][i]) ;


        KAV_Invariant



        Сообщ.
        #19

        ,
        24.02.04, 08:07

          Кстати, вместо блока try…catch можно использовать функцию StrToFloatDef. Её смысл заключается в следующем. Она, как и StrToFloat, преобразует строку в число с плавающей точкой. Но та, если строка числом не является, вызывает исключение. В этой функции на такой случай есть второй параметр — число, и, если подлежащая конвертированию строка — не число, то нет никакого исключения, а подставляется значение по умолчанию — как раз второй параметр. Тогда код считывания будет выглядеть так:

          ExpandedWrap disabled

            double Values[29];

            for( int i=0; i < 29; i++ )

              Values[i] = StrToFloatDef(StringGrid1->Cells[0][i],0);

          Сообщение отредактировано: KAV — 24.02.04, 08:10


          compaq



          Сообщ.
          #20

          ,
          24.02.04, 08:30

            Full Member

            ***

            Рейтинг (т): 0

            Вот я тут кое что написал вы не могли бы подсказать что не так
            Задание
            “Дан вектор, содержащий не более 29 элементов. Построить новый, элементы которого — величины, обратные заданным (нулевые элементы не заменять). Подсчитать количество не изменившихся элементов. Найти максимальный по абсолютной величине отрицательный элемент и общее количество отрицательных элементов. Формат числа ?ццц. Вид распечатки результатов разработать самостоятельно.”

            Вот что я наковырял

            ExpandedWrap disabled

              void __fastcall TForm1::Button1Click(TObject *Sender)

              {

              double A[29];

              int i;

              for( i=0; i < 29; i++ ) {

                 try{

                    A[i] = StringGrid1->Cells[0][i].ToDouble();

                 } catch( … ) {

                    A[i] = 0;

                 }

              }

              double B[29];

              int kol1=0;

              int kol2=0;

              int max=0;

              for(i=0;i<29;i++)

              {

                 if(A[i]==0)

                 {

                    B[i]=A[i];

                    kol1++;

                 }

                 else B[i]1=/float(A[i])

                 if(B[i]<0)

                 {

                    kol2++;

                    if(abs(B[i])>max)max=B[i];

                 }

                 for( i=0; i < 29; i++ ) {

                    try{

                       StringGrid1->Cells[2][i] = AnsiString(,i,B[i]);

                    } catch( … ) {

                    }

                 }

                 Edit1->Text=kol1;

                 Edit2->Text=kol2;

                 Edit3->Text=max;

              }

              }

            Вот ошибки

            [C++ Error] Unit1.cpp(40): E2379 Statement missing ;
            [C++ Error] Unit1.cpp(46): E2379 Statement missing ;
            Что не так я сделал до меня что то не доходит. Не всё же у меня прогресс на лицо неделю назад я даже о подобном и мечтать не мог спасибо вам большое за помощь.

            :)

            Сообщение отредактировано: trainer — 24.02.04, 08:49


            trainer



            Сообщ.
            #21

            ,
            24.02.04, 08:52

              Цитата

              compaq, 24.02.04, 11:30
              else B[i]1=/float(A[i])

              Нет ‘;’ после оператора, ‘1’ непонятно где.
              Второй for вставлен не туда. Должно быть что-то вроде:

              Цитата

              void __fastcall TForm1::Button1Click(TObject *Sender)
              {
              double A[29];
              int i;
              for( i=0; i < 29; i++ ) {
              try{
              A[i] = StringGrid1->Cells[0][i].ToDouble();
              } catch( … ) {
              A[i] = 0;
              }
              }
              double B[29];
              int kol1=0;
              int kol2=0;
              int max=0;
              for(i=0;i<29;i++)
              {
              if(A[i]==0)
              {
              B[i]=A[i];
              kol1++;
              }

              else B[i]1 = /float(A[i])

              // здесь что-то непонятное
              else B[i] = 1/A[i]; // по идее, должно бы быть так
              if(B[i]<0)
              {
              kol2++;
              if(abs(B[i])>max)max=B[i];
              }
              } // по идее, должно бы быть здесь
              for( i=0; i < 29; i++ ) {
              try{
              StringGrid1->Cells[2][i] = AnsiString(,i,B[i]);
              } catch( … ) {
              }
              }
              Edit1->Text=kol1;
              Edit2->Text=kol2;
              Edit3->Text=max;

              }

              // по идее, здесь быть не должно
              }

              про правильность самого алгоритма ничего сказать не могу.

              Добавлено в 24.02.04, 09:05:
              P.S. kol1 и kol2 какие функции выполняют?

              Сообщение отредактировано: trainer — 24.02.04, 09:04


              compaq



              Сообщ.
              #22

              ,
              24.02.04, 17:16

                Full Member

                ***

                Рейтинг (т): 0

                А как сделать так что бы StringGrid заполнялся не с 1(фиксируемого) столбца а со второго.
                Извените за идиотские вопросы но в книжке архангельского не чего подобного нет.

                Добавлено в 24.02.04, 17:42:
                А как сделать так что бы StringGrid заполнялся не с 1(фиксируемого) столбца а со второго.
                То есть массив у меня заполняется с 1 (фиксируемой) ячейкой а мне надо что бы он заполнялся со второй.
                И ещё а в билдере есть токой же элемент как в бейсике Input Box


                compaq



                Сообщ.
                #23

                ,
                24.02.04, 20:52

                  Full Member

                  ***

                  Рейтинг (т): 0

                  Простите пожалуйста но у меня опять не чего не выходит я ту не мног ошибся с заданием мне нужно что бы пользователь сам выбирал размерность массива но его размер не превышал бы 29 ну так вот где надо объявить глобальную переменную которую можно поставить в массив то есть в место A[29] A[z] а пользователь вводил бы его сам но там была бы проверка такова плана
                  И как можно считывать из StringGrid минуя 1 фиксируемый столбец.

                  //—————————————————————————

                  #include <vcl.h>
                  #pragma hdrstop

                  #include «Unit1.h»
                  //—————————————————————————
                  #pragma package(smart_init)
                  #pragma resource «*.dfm»
                  TForm1 *Form1;
                  //—————————————————————————
                  __fastcall TForm1::TForm1(TComponent* Owner)
                  : TForm(Owner)
                  {

                  AnsiString z
                  AnsiString s = InputBox(«bla-bla-bla»,»??-??-??»,»»);
                  if(s>29)s=29;
                  z=s
                  else
                  Close();

                  }
                  //—————————————————————————

                  void __fastcall TForm1::Button1Click(TObject *Sender)
                  {
                  extern AnsiString z;
                  double A[z];
                  int i;
                  for( i=0; i <z; i++ ) {
                  try{
                  A[i] = StringGrid1->Cells[1][i].ToDouble();
                  } catch( … ) {
                  A[i] = 0;
                  }
                  }
                  double B[z];
                  int kol1=0;
                  int kol2=0;
                  int max=0;
                  for(i=0;i<z;i++)
                  {
                  if(A[i]==0)
                  {
                  B[i]=A[i];
                  kol1++;
                  }
                  //else B[i]1 = /float(A[i]) // ????? ???-?? ??????????
                  else B[i] = 1/A[i]; // ?? ????, ?????? ?? ???? ???
                  if(B[i]<0)
                  {
                  kol2++;
                  if(abs(B[i])>max)max=B[i];
                  }
                  } // ?? ????, ?????? ?? ???? ?????
                  for( i=0; i <z; i++ ) {
                  try{
                  StringGrid1->Cells[2][i] = AnsiString(B[i]);
                  } catch( … ) {
                  }
                  }
                  Edit1->Text=kol1;
                  Edit2->Text=kol2;
                  Edit3->Text=max;
                  }

                  [C++ Error] Unit1.cpp(16): E2108 Improper use of typedef ‘AnsiString’
                  [C++ Error] Unit1.cpp(16): E2379 Statement missing ;
                  [C++ Error] Unit1.cpp(18): E2451 Undefined symbol ‘s’
                  [C++ Error] Unit1.cpp(19): E2451 Undefined symbol ‘z’
                  [C++ Error] Unit1.cpp(20): E2379 Statement missing ;
                  [C++ Error] Unit1.cpp(30): E2313 Constant expression required
                  [C++ Error] Unit1.cpp(39): E2313 Constant expression required


                  trainer



                  Сообщ.
                  #24

                  ,
                  25.02.04, 05:25

                    Ну а символы ‘;’ в конце операторов кто ставить будет? :)
                    Размерность у массивов должна быть целочисленная, а не AnsiString :)


                    compaq



                    Сообщ.
                    #25

                    ,
                    25.02.04, 11:41

                      Full Member

                      ***

                      Рейтинг (т): 0

                      Так я пытался но у меня так не чего и не вышло

                      ExpandedWrap disabled

                        //—————————————————————————

                        #include <vcl.h>

                        #pragma hdrstop

                        #include «Unit1.h»

                        //—————————————————————————

                        #pragma package(smart_init)

                        #pragma resource «*.dfm»

                        TForm1 *Form1;

                        //—————————————————————————

                        __fastcall TForm1::TForm1(TComponent* Owner)

                        : TForm(Owner)

                        {

                        int z;

                        AnsiString s = InputBox(«bla-bla-bla»,»??-??-??»,»»);

                        if(s>29)s=29;

                        z=IntToStr(s);

                        else

                        Close();

                        }

                        //—————————————————————————

                        void __fastcall TForm1::Button1Click(TObject *Sender)

                        {

                        extern int z;

                        double A[z];

                        int i;

                        for( i=0; i <z; i++ ) {

                        try{

                        A[i] = StringGrid1->Cells[1][i].ToDouble();

                        } catch( … ) {

                        A[i] = 0;

                        }

                        }

                        double B[z];

                        int kol1=0;

                        int kol2=0;

                        int max=0;

                        for(i=0;i<z;i++)

                        {

                        if(A[i]==0)

                        {

                        B[i]=A[i];

                        kol1++;

                        }

                        else B[i] = 1/A[i];

                        if(B[i]<0)

                        {

                        kol2++;

                        if(abs(B[i])>max)max=B[i];

                        }

                        }

                        for( i=0; i <z; i++ ) {

                        try{

                        StringGrid1->Cells[2][i] = AnsiString(B[i]);

                        } catch( … ) {

                        }

                        }

                        Edit1->Text=kol1;

                        Edit2->Text=kol2;

                        Edit3->Text=max;

                        }

                        //—————————————————————————

                        [C++ Error] Unit1.cpp(19): E2285 Could not find a match for ‘IntToStr(AnsiString)’

                        [C++ Error] Unit1.cpp(20): E2054 Misplaced else

                        [C++ Error] Unit1.cpp(30): E2313 Constant expression required

                        [C++ Error] Unit1.cpp(39): E2313 Constant expression required

                      И ещё я правильно объявил z она будет глобальной переменной или нет мне нужно что бы она была глобальной. Вы уж меня простите за идиотские вопросы вот только всё напишу и уйду в подполье нормально изучать язык.

                      Сообщение отредактировано: compaq — 25.02.04, 11:44


                      trainer



                      Сообщ.
                      #26

                      ,
                      25.02.04, 13:10

                        Цитата

                        compaq, 25.02.04, 14:41
                        [C++ Error] Unit1.cpp(19): E2285 Could not find a match for ‘IntToStr(AnsiString)’

                        Нет такой функции, надо писать:

                        ExpandedWrap disabled

                          z=StrToInt(s); // или StrToIntDef

                        или

                        ExpandedWrap disabled

                          z = s.ToInt(); // или ToIntDef

                        Цитата

                        compaq, 25.02.04, 14:41
                        [C++ Error] Unit1.cpp(20): E2054 Misplaced else

                        Между if и else не может быть двух операторов — или один обыкновенный или один составной. Вот здесь:

                        Цитата

                        if(s>29)s=29;
                        z=IntToStr(s);

                        else

                        Цитата

                        compaq, 25.02.04, 14:41
                        [C++ Error] Unit1.cpp(30): E2313 Constant expression required

                        Для задания размерности массива должно использоваться константное выражение. для переменного — надо использовать оператор new. Вот здесь:

                        Цитата

                        extern int z;
                        double A[z];

                        заменить на

                        ExpandedWrap disabled

                          extern int z;

                          double * A = new double[z];

                        и не забыть потом, когда массив будет не нужен, сделать delete [] A;

                        Цитата

                        compaq, 25.02.04, 14:41
                        double B[z];

                        Аналогично.

                        Сообщение отредактировано: trainer — 25.02.04, 13:13


                        Adil



                        Сообщ.
                        #27

                        ,
                        25.02.04, 13:23

                          Цитата compaq @ 25.02.04, 12:41

                          Так я пытался но у меня так не чего и не вышло

                          Тебе надо еще попытаться понять что за ошибки пишет компилятор :rolleyes:
                          [C++ Error] Unit1.cpp(19): E2285 Could not find a match for ‘IntToStr(AnsiString)’
                          По названию функции понятно, что она преводит целое в строку, а тебе надо наоброт!!!
                          Используй лучше AnsiString::ToIntDef
                          Если ты хочешь использовать z и в void __fastcall TForm1::Button1Click(TObject *Sender)
                          то надо объявить z глобальной переменной (вне функций)
                          (хотя еще правильней сделать ее членом класса TForm1)
                          [C++ Error] Unit1.cpp(20): E2054 Misplaced else
                          Если хочешь, что бы под if выполнялось несколько операторов, надо объединять их в фигурные скобки

                          ExpandedWrap disabled

                            if(s>29)

                            {

                              s=29;

                              z=IntToStr(s);

                            }

                            else

                              Close();

                          И привыкай форматировать текст, самому ж легче будет разбираться!
                          [C++ Error] Unit1.cpp(30): E2313 Constant expression required
                          статический массив можно объявлять размерностью, которая задается только как константа
                          int A[20];
                          или
                          #define __N 100
                          int A[__N];

                          extern int z;???
                          так ссылаются только на переменные, объявленные в другом срр-файле
                          Если б у тебя дело дошло до линковки, линкер бы выругался «unresolved external _z in unit1.obj»

                          ExpandedWrap disabled

                            //—————————————————————————

                            #include <vcl.h>

                            #include <math.h>

                            #include <values.h>

                            #include <stdlib.h>

                            #pragma hdrstop

                            #include «Unit1.h»

                            //—————————————————————————

                            #pragma package(smart_init)

                            #pragma resource «*.dfm»

                            TForm1 *Form1;

                            //—————————————————————————

                            int z=29;//видна для всех функций в этом файле

                            __fastcall TForm1::TForm1(TComponent* Owner)

                            : TForm(Owner)

                            {

                            }

                            //—————————————————————————

                            //добавь обработчик OnCreate для формы

                            void __fastcall TForm1::FormCreate(TObject *Sender)

                            {

                              z = InputBox(«bla-bla-bla»,»??-??-??»,»29″).ToIntDef(29);

                              StringGrid1->RowCount=z+1;

                              StringGrid1->ColCount=3;

                              StringGrid1->FixedCols=1;

                              StringGrid1->FixedRows=1;

                              StringGrid1->Cells[0][0]=»##»;

                              StringGrid1->Cells[1][0]=»Вектор А»;

                              StringGrid1->Cells[2][0]=»Вектор B»;

                              for(int i=1;i<=z;i++)

                              {

                                StringGrid1->Cells[0][i]=i;

                                StringGrid1->Cells[1][i]=50-random(101);//СВ от -50 до 50

                              }

                            }

                            void __fastcall TForm1::Button1Click(TObject *Sender)

                            {

                              //double A=new double[z]; //так отводят память под динамический массив

                              //хотя здеся можно и без них обойтись

                              double A, B, max;

                              int kol1=0;

                              int kol2=0;

                              for(int i=0;i<z;i++)

                              {

                                try{

                                  //i+1 — тогда начнет со второй строки  

                                  A = StringGrid1->Cells[1][i+1].ToDouble();//и где это kav нашел StrToFloatDef???

                                }catch(…){

                                   A=0.;

                                }

                                if(fabs(A)<MINDOUBLE)//не советую сравнивать double с 0 «напрямую», может и не сработать

                                {

                                  B=A[i];

                                  kol1++;

                                }

                                else

                                {

                                   B = 1./A;

                                   if(B<0)

                                   {

                                     kol2++;

                                     //максимальный по модулю из отрицательных — просто наименьший

                                     // а уж использовать abs()! — он же отбрасывает мантиссу и возвращает int!

                                     if(B[i]<max)max=B[i];

                                   }

                                }

                                StringGrid1->Cells[2][i+1] = AnsiString(B);//try-catch был лишним

                              }

                              Edit1->Text=kol1;

                              Edit2->Text=kol2;

                              Edit3->Text=max;

                            }

                            //—————————————————————————

                          писАл на вскидку…


                          compaq



                          Сообщ.
                          #28

                          ,
                          25.02.04, 15:14

                            Full Member

                            ***

                            Рейтинг (т): 0

                            И наконец последний вопрос(надеюсь) что это за ошибка.

                            ExpandedWrap disabled

                              //—————————————————————————

                              #include <vcl.h>

                              #pragma hdrstop

                              #include «Unit1.h»

                              //—————————————————————————

                              #pragma package(smart_init)

                              #pragma resource «*.dfm»

                              TForm1 *Form1;

                              //—————————————————————————

                              __fastcall TForm1::TForm1(TComponent* Owner)

                              : TForm(Owner)

                              {

                              static int z;

                              AnsiString s = InputBox(«bla-bla-bla»,»??-??-??»,»»);

                              if (s<=29)

                                z=StrToInt(s);

                              else

                                Close();

                              }

                              //—————————————————————————

                              void __fastcall TForm1::Button1Click(TObject *Sender)

                              {

                              extern int z;

                              double * A = new double[z];

                              int i;

                              for( i=0; i <z; i++ ) {

                              try{

                              A[i] = StringGrid1->Cells[1][i].ToDouble();

                              } catch( … ) {

                              A[i] = 0;

                              }

                              }

                              double * B = new double[z];

                              int kol1=0;

                              int kol2=0;

                              int max=0;

                              for(i=0;i<z;i++)

                              {

                              if(A[i]==0)

                              {

                              B[i]=A[i];

                              kol1++;

                              }

                              else B[i] = 1/A[i];

                              if(B[i]<0)

                              {

                              kol2++;

                              if(abs(B[i])>max)max=B[i];

                              }

                              }

                              for( i=0; i <z; i++ ) {

                              try{

                              StringGrid1->Cells[2][i] = AnsiString(B[i]);

                              } catch( … ) {

                              }

                              }

                              Edit1->Text=kol1;

                              Edit2->Text=kol2;

                              Edit3->Text=max;

                              }

                              //—————————————————————————

                              [Linker Error] Unresolved external ‘_z’ referenced from C:C++ОДНОМЕРНЫЕ МАССЫВЫUNIT1.OBJ


                            trainer



                            Сообщ.
                            #29

                            ,
                            25.02.04, 15:22

                              Ну переменную то где-то надо бы и объявить:
                              int z;
                              Кстати, ее объявление надо бы вынести из конструктора формы на глобальный уровень(перед конструктором например). Тогда и extern не нужен.

                              Сообщение отредактировано: trainer — 25.02.04, 15:23


                              Adil



                              Сообщ.
                              #30

                              ,
                              25.02.04, 15:23

                                2compaq:Ты хоть ответы-то читаешь? :angry:
                                Прочитай мой предыдущий ответ по-внимательнее…

                                Сообщение отредактировано: Adil — 25.02.04, 15:24

                                0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)

                                0 пользователей:

                                • Предыдущая тема
                                • Borland C++ Builder/Turbo C++ Explorer
                                • Следующая тема

                                [ Script execution time: 0,0687 ]   [ 16 queries used ]   [ Generated: 21.06.23, 23:30 GMT ]  

                              • Mise 605 indesit коды ошибок
                              • Mirrors edge ошибка при запуске приложения 0xc0000906
                              • Mirrors edge ошибка application load error 5 0000065434
                              • Mirrors edge ошибка 0xc000007b
                              • Mirrors edge exe ошибка