Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > IT форум > Помощь студентам
Регистрация

Восстановить пароль

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 15.03.2014, 00:44   #1
guroDragon
Пользователь
 
Регистрация: 09.09.2013
Сообщений: 83
По умолчанию C поворот матрицы на на 90 градусов за час. стрелкой.

Все та же матрица.
День назад просил вас помочь с написанием кода, уже сам сделал. Просто глянул, то что вы мне кинули, не все еще знаю, не все выучил, а тут, мой код, вроде в разы легче.
Но вот в чем проблема:
Делал менюшку с помощью switch'a, что бы пока юзер не нажмёт esc, прога не закрывалась.
Все вроде пашет нормас, но!!
Если я в case 13 (сам переворот матрицы и вывод её на экран, короче самый сок) все закоменчу, свитч пашет, всё хорошо, но если не коментить, при нажатии любой клавиши, после того, как прога выведет мне перевёрнутую матрицу, вместо возврата к менюшке, прога тупит 1 сек, а потом просто глохнит. Хотя сам код, по перевороту матрицы работает отлично.
Помогите разобраться в чем проблема.
Спасибо.

Код:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>

int main ()
{
	unsigned s;
	int i,j,k;
	char c;
	while (!(c==27))
	{
		printf("          Laborotory work #3\n");
        printf("    Performed by AListratenko Nikita\n");
        printf("                KM-31\n");
    	printf("             Variant #1\n");
        printf("                          24/02/2014\n\n\n");
        printf(" Enter - run the program.\n");
        printf(" Esc - exit.\n");
        printf(" Any other key - information about program.\n");
        c=getch();
        system("cls");
		switch (c)
		{
			case 13:
				//--------------------------------------------------------------------------- Вот эту часть на закоментить, что бы прога не вылетала.
				printf("Enter a size of the array:");													
				scanf("%d",&s);
				int array[s][s];
				int arrayN[s][s];
				if (s>5)
				{
					for (i=0;i<s;i++)
					{
						for (j=0;j<s;j++)
						{
							array[i][j]=rand() %9;
							arrayN[i][j]=array[i][j];
						}
					}
				}
				else 
				{
					for (i=0;i<s;i++)
					{
						for (j=0;j<s;j++)
						{
							printf("Enter %d.%d element of the array.",i+1,j+1);
							scanf("%d",&array[i][j]);
							arrayN[i][j]=array[i][j];
						}
					}
				}
				printf("Entered array:\n");
				for (i=0;i<s;i++)
				{
					for (j=0;j<s;j++)
					{
						printf("%d ",array[i][j]);
					}
					printf("\n");
				}
				printf("\nNew array:\n");
				for (i=0;i<s;i++)
				{
					k=s;
					for (j=0;j<s;j++)
					{
						k--;
						arrayN[i][j]=array[k][i];
						printf("%d ",arrayN[i][j]);
					}
					printf("\n");
				}
				//---------------------------------------------------------------------
				printf("  Esc - exit.\n"); 
                printf("  Any other - go to the main page.\n");
				c=getch();
				system("cls");
				break;
				
			case 27:
				break;
				
			default:
				printf("\n This program makes a rotation by 90 degrees for clockwise.\n"); 
				printf("If the entered size of the array is more than 5 program will fill array randomly;\n");
				printf("If the entered size of the array is less than 5 user will have to fill it by his own.\n");
				printf("  Esc - exit.\n"); 
                printf("  Any other - go to the main page.\n");
				c=getch();
				system("cls");
				break;
		}
	}
	return 0;
	
	
	
}
Вложения
Тип файла: txt Новый текстовый документ.txt (2.4 Кб, 113 просмотров)

Последний раз редактировалось Stilet; 15.03.2014 в 13:51.
guroDragon вне форума Ответить с цитированием
Старый 15.03.2014, 02:20   #2
BDA
МегаМодератор
СуперМодератор
 
Аватар для BDA
 
Регистрация: 09.11.2010
Сообщений: 7,427
По умолчанию

Код:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>

int
main()
{
    unsigned s;
    int i, j;
    char c = 0;
    int **a, **b;
    while (c != 27) {
        printf("          Laborotory work #3\n");
        printf("    Performed by AListratenko Nikita\n");
        printf("                KM-31\n");
        printf("             Variant #1\n");
        printf("                          24/02/2014\n\n\n");
        printf(" Enter - run the program.\n");
        printf(" Esc - exit.\n");
        printf(" Any other key - information about program.\n");
        c = getch();
        system("cls");
        switch (c)
        {
            case 13:
                printf("Enter a size of the array:");
                scanf("%d", &s);
                a = calloc(s, sizeof(int*));
                b = calloc(s, sizeof(int*));
                for (i = 0; i < s; ++i) {
                    a[i] = calloc(s, sizeof(int));
                    b[i] = calloc(s, sizeof(int));
                }
                if (s > 5)
                    for (i = 0; i < s; ++i)
                        for (j = 0; j < s; ++j)
                            a[i][j] = b[i][j] = rand() % 9;
                else
                    for (i = 0; i < s; ++i)
                        for (j = 0; j < s; ++j) {
                            printf("Enter %d.%d element of the array.", i + 1, j + 1);
                            scanf("%d", &a[i][j]);
                        }
                printf("Entered array:\n");
                for (i = 0; i < s; ++i) {
                    for (j = 0; j < s; ++j)
                        printf("%d ", a[i][j]);
                    printf("\n");
                }
                printf("\nNew array:\n");
                for (i = 0; i < s; ++i) {
                    for (j = 0; j < s; ++j)
                        printf("%d ", b[i][j] = a[s - 1 - j][i]);
                    printf("\n");
                }
                for (i = 0; i < s; ++i) {
                    free(a[i]);
                    free(b[i]);
                }
                free(a);
                free(b);
                printf("Proga");
                printf("  Esc - exit.\n");
                printf("  Any other - go to the main page.\n");
                c = getch();
                system("cls");
                break;

            case 27:
                break;

            default:
                printf("\n This program makes a rotation by 90 degrees for clockwise.\n");
                printf("If the entered size of the array is more than 5 program will fill array randomly;\n");
                printf("If the entered size of the array is less than 5 user will have to fill it by his own.\n");
                printf("  Esc - exit.\n");
                printf("  Any other - go to the main page.\n");
                c = getch();
                system("cls");
                break;
        }
    }
    return 0;
}
Чуть переписал (CodeBlocks не понравилось объявление массива в свитче).
Пишите язык программирования - это форум программистов, а не экстрасенсов. (<= это подпись )
BDA на форуме Ответить с цитированием
Старый 15.03.2014, 02:22   #3
Smogg
Участник клуба
 
Регистрация: 14.06.2011
Сообщений: 1,138
По умолчанию

закидоны компилятора. Моя старенькая VS2010 из-под винды не видит ничего странного:
Код:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>

	int main ()
{
	unsigned s;
	int i,j,k;
	char c = 0;
	while (c!=27)
	{
		printf(" Laborotory work #3\n");
		printf(" Performed by AListratenko Nikita\n");
		printf(" KM-31\n");
		printf(" Variant #1\n");
		printf(" 24/02/2014\n\n\n");
		printf(" Enter - run the program.\n");
		printf(" Esc - exit.\n");
		printf(" Any other key - information about program.\n");
		c=getch();
		system("cls");
		switch (c)
		{
		case 13:
			//--------------------------------------------------------------------------- Вот эту часть на закоментить, что бы прога не вылетала.
			printf("Enter a size of the array:");
			scanf("%d",&s);
			if(s>99) s = 99;
			if (s<1) s = 5;
			int array[99][99];
			int arrayN[99][99];
			if (s>5)
			{
				for (i=0;i<s;i++)
				{
					for (j=0;j<s;j++)
					{
						array[i][j]=rand() %9;
						arrayN[i][j]=array[i][j];
					}
				}
			}
			else
			{
				for (i=0;i<s;i++)
				{
					for (j=0;j<s;j++)
					{
						printf("Enter %d.%d element of the array.",i+1,j+1);
						scanf("%d",&array[i][j]);
						arrayN[i][j]=array[i][j];
					}
				}
			}
			printf("Entered array:\n");
			for (i=0;i<s;i++)
			{
				for (j=0;j<s;j++)
				{
					printf("%d ",array[i][j]);
				}
				printf("\n");
			}
			printf("\nNew array:\n");
			for (i=0;i<s;i++)
			{
				k=s;
				for (j=0;j<s;j++)
				{
					k--;
					arrayN[i][j]=array[k][i];
					printf("%d ",arrayN[i][j]);
				}
				printf("\n");
			}
			//---------------------------------------------------------------------
			printf(" Esc - exit.\n");
			printf(" Any other - go to the main page.\n");
			c=getch();
			system("cls");
			break;

		case 27:
			break;

		default:
			printf("\n This program makes a rotation by 90 degrees for clockwise.\n");
			printf("If the entered size of the array is more than 5 program will fill array randomly;\n");
			printf("If the entered size of the array is less than 5 user will have to fill it by his own.\n");
			printf(" Esc - exit.\n");
			printf(" Any other - go to the main page.\n");
			c=getch();
			system("cls");
			break;
		}
	}
	return 0;
}
Smogg вне форума Ответить с цитированием
Старый 15.03.2014, 02:25   #4
Smogg
Участник клуба
 
Регистрация: 14.06.2011
Сообщений: 1,138
По умолчанию

Цитата:
Сообщение от BDA Посмотреть сообщение
Чуть переписал (CodeBlocks не понравилось объявление массива в свитче).
А если внутренность свитчевого кейса заключить в скобки?
Код:
case 13:
{
   .... 
   ...
}
break;
?

Ps^ псмотрел на свой код и увидел, что и у меня без скобок нормально объявляется массив... Хотя обычно не дает объявлять переменные... Пишет что-то вроде "из-за кейса пропущено объявление.".

Последний раз редактировалось Smogg; 15.03.2014 в 02:29.
Smogg вне форума Ответить с цитированием
Старый 15.03.2014, 02:36   #5
guroDragon
Пользователь
 
Регистрация: 09.09.2013
Сообщений: 83
По умолчанию

Цитата:
Сообщение от Smogg Посмотреть сообщение
А если внутренность свитчевого кейса заключить в скобки?
Код:
case 13:
{
   .... 
   ...
}
break;
?

Ps^ псмотрел на свой код и увидел, что и у меня без скобок нормально объявляется массив... Хотя обычно не дает объявлять переменные... Пишет что-то вроде "из-за кейса пропущено объявление.".
Спасибо большое, о скобах не подумал.
Все пашет)
guroDragon вне форума Ответить с цитированием
Старый 15.03.2014, 02:37   #6
guroDragon
Пользователь
 
Регистрация: 09.09.2013
Сообщений: 83
По умолчанию

Цитата:
Сообщение от BDA Посмотреть сообщение
Код:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>

int
main()
{
    unsigned s;
    int i, j;
    char c = 0;
    int **a, **b;
    while (c != 27) {
        printf("          Laborotory work #3\n");
        printf("    Performed by AListratenko Nikita\n");
        printf("                KM-31\n");
        printf("             Variant #1\n");
        printf("                          24/02/2014\n\n\n");
        printf(" Enter - run the program.\n");
        printf(" Esc - exit.\n");
        printf(" Any other key - information about program.\n");
        c = getch();
        system("cls");
        switch (c)
        {
            case 13:
                printf("Enter a size of the array:");
                scanf("%d", &s);
                a = calloc(s, sizeof(int*));
                b = calloc(s, sizeof(int*));
                for (i = 0; i < s; ++i) {
                    a[i] = calloc(s, sizeof(int));
                    b[i] = calloc(s, sizeof(int));
                }
                if (s > 5)
                    for (i = 0; i < s; ++i)
                        for (j = 0; j < s; ++j)
                            a[i][j] = b[i][j] = rand() % 9;
                else
                    for (i = 0; i < s; ++i)
                        for (j = 0; j < s; ++j) {
                            printf("Enter %d.%d element of the array.", i + 1, j + 1);
                            scanf("%d", &a[i][j]);
                        }
                printf("Entered array:\n");
                for (i = 0; i < s; ++i) {
                    for (j = 0; j < s; ++j)
                        printf("%d ", a[i][j]);
                    printf("\n");
                }
                printf("\nNew array:\n");
                for (i = 0; i < s; ++i) {
                    for (j = 0; j < s; ++j)
                        printf("%d ", b[i][j] = a[s - 1 - j][i]);
                    printf("\n");
                }
                for (i = 0; i < s; ++i) {
                    free(a[i]);
                    free(b[i]);
                }
                free(a);
                free(b);
                printf("Proga");
                printf("  Esc - exit.\n");
                printf("  Any other - go to the main page.\n");
                c = getch();
                system("cls");
                break;

            case 27:
                break;

            default:
                printf("\n This program makes a rotation by 90 degrees for clockwise.\n");
                printf("If the entered size of the array is more than 5 program will fill array randomly;\n");
                printf("If the entered size of the array is less than 5 user will have to fill it by his own.\n");
                printf("  Esc - exit.\n");
                printf("  Any other - go to the main page.\n");
                c = getch();
                system("cls");
                break;
        }
    }
    return 0;
}
Чуть переписал (CodeBlocks не понравилось объявление массива в свитче).
Спасибо за помощь.
Посижу, поразбираю твой код)
guroDragon вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
C поворот матрицы на на 90 градусов за час. стрелкой. guroDragon Помощь студентам 1 14.03.2014 09:02
поворот матрицы на 180 градусов Felixjkee Помощь студентам 0 09.01.2013 11:18
поворот матрицы на 180 и 270 градусов Alex1123 Помощь студентам 4 25.05.2011 18:31
Поворот матрицы на 90 градусов. Что не так? Nice_nastya Общие вопросы C/C++ 8 22.05.2011 17:41
Поворот матрицы на 90 градусов Альбиша Помощь студентам 2 26.05.2010 01:19