Ir para conteúdo
Fórum Script Brasil
  • 0

dúvida: programa básico em C


Guest piteko

Pergunta

então pessoal, sou novo em programação( estou na quinta aula) e gostaria de pedir a ajuda de vocês sobre um programa basicão em C: tirar as raízes de uma equação de segundo grau... o codigo é esse:

#include <stdio.h>

#include <math.h>

int main(void)

{

float a;

float b;

float c;

float x1;

float x2;

float delta;

printf("Trabalho de Programacao:\n Entre Com os valores de A,B,C:\n");

scanf("%F %F %F",&a,&b,&c);

delta =((b*B)-(4*a*c));

x1 =((-b + sqrt(delta))/2*a);

x2 =((-b - sqrt(delta))/2*a);

printf("As raizes são x1=%F e x2=%F \n \n \n \n" ,x1,x2);

system("PAUSE");

return 0;

}

estou usando o Dev C++ e quando vou rodar, não aparece o resultado, o que pode ser??

obrigado.

Link para o comentário
Compartilhar em outros sites

5 respostass a esta questão

Posts Recomendados

  • 0

O sqrt do C não funciona com float.

Se você puder usar C++, conseguirá usar o sqrt com o tipo float.

No caso do C, ainda tem essa função feita pelo John Carmack da id Software.

O copyright dela é GPL.

float Q_rsqrt( float number )
{
  long i;
  float x2, y;
  const float threehalfs = 1.5F;

  x2 = number * 0.5F;
  y  = number;
  i  = * ( long * ) &y;  // evil floating point bit level hacking
  i  = 0x5f3759df - ( i >> 1 ); // what the fuck?
  y  = * ( float * ) &i;
  y  = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
  // y  = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed

  #ifndef Q3_VM
  #ifdef __linux__
    assert( !isnan(y) ); // bk010122 - FPE?
  #endif
  #endif
  return y;
}

Nunca testei, mas pelos comentários, funciona.

Abraços.

Link para o comentário
Compartilhar em outros sites

  • 0
O sqrt do C não funciona com float.

Funciona sim.

#include <stdio.h>
#include <math.h>
int main(void) {
   float numero = 45.56;
   printf("%f\n",sqrt(numero));
   printf("%f\n",sqrtf(numero));
   return 0;
}

linux-0khy:>gcc -g -Wall raiz.c

linux-0khy:>./a.out

5.878776

5.878775

Link para o comentário
Compartilhar em outros sites

  • 0

opaa...sou novo aki no forum e toh com uma duvida tb em programacao de nivel basico...

criei um game de snake no console em c++. tipow...eu usei uma logica diferente porque foi a unica saida q eu encontrei pra criar um snake com o que eu sei....

eu vi um codigo em um outro forum que deu um tanto de arquivo e biblioteca..... já o meu só deu um arquivo mesmo xD!!

a logica dele é simples...ele adiciona um ponto a frent da atual cabeça e depois o atribui para uma variavel cauda(tail) e segue todos

os pontos proximos por if....

o foda é que quando ela axa mais de um caminho possivel dá bug...entaum eu usei algo parecido com um bool para poder tirar a

probabilidade de ir nos dois caminhos... o problema é q se a cobra ir para o ponto errado (ela sempre faz isso....oxe danada!!!)babaus...

entaum eu usei uma função ow coisa parecida para determinar um nivel de prioridade para q ela faça sempre a escolha certa.....

só depoois eu percebi que quando ela tah muito grande...e passa do lado de seu corpo duas ow tres vezes gera um conflito não identificado

onde deduzo ser por causa da prioridade. este conflito faz com que o jogo congele e tals.....fora essa situação...q só acontece quando você

já tah lá para 400 pontos no nivel 2 de velocidade...(ow 800 pontos no nivel 5) q dá esses pals kabulosos..

#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;

void MAP();
void CONTROL();
void FOOD();
void PRIORITY();

int option, i, j, tail_x, tail_y, food_x, food_y, priority;
const int com = 20, lar = 50;
int block [com][lar];
int snake_x = 10, snake_y = 25, head_x = -1, head_y = 0, size = 3, off = 0, points = 0;
int speed = 2, pr_u = 1, pr_d = 2, pr_l = 3, pr_r = 4;
char key2, key = 'w', key_up = 'w', key_down = 's', key_left = 'a', key_right = 'd';
bool end = false, upgrade = false, start_food = false, r = false, l = false, u = true, d = false, end_turn = false;

int main()
{
    do
    {
        system("color 1f");
        cout<<"\n\n\t\t\t    SNAKE --- NEW VERSION\n\n";
        cout<<"\t\t    This Game is a product by Lukaum\n\n\n\n";
        if (key == 'x')
        {
            cout<<"0_ Continue\n";
        }
        cout<<"1_ Play\n";
        cout<<"2_ Instructions\n";
        cout<<"3_ Option\n";
        cout<<"4_ Exit\n";
        cin>>option;
        if (option == 1 || (option == 0 && key == 'x'))
        {
            system("cls");
            if (option == 0 && key == 'x')
            {
                key = key_up;
            }
            else
            {
                snake_x = 10, snake_y = 25, head_x = -1, head_y = 0, size = 3, off = 0, points = 0;
                key = key_up;
                start_food = false;
                for (i = 0; i < com; i++)
                {
                    for (j = 0; j < lar; j++)
                    {
                        block [i][j] = ' ';
                    }
                }
                for (i = 0; i < com; i++)
                {
                    block [i][0] = char(186);
                    block [i][lar - 1] = char(186);
                }
                for (j = 0; j < lar; j++)
                {
                    block [0][j] = char(205);
                    block [com - 1][j] = char(205);
                }
                block [0][0] = char(201);
                block [com - 1][0] = char(200);
                block [0][lar - 1] = char(187);
                block [com - 1][lar - 1] = char(188);
                block [snake_x][snake_y] = char(254);
                block [snake_x + 1][snake_y] = char(254);
                block [snake_x + 2][snake_y] = char(254);
            }
            do
            {
                MAP();
                FOOD();
                CONTROL();
                snake_x += head_x;
                snake_y += head_y;
                if (block [snake_x][snake_y] == char(186) || block [snake_x][snake_y] == char(205) || block [snake_x][snake_y] == char(254))
                {
                    end = true;
                }
                else
                {
                    if (block [snake_x][snake_y] == '*')
                    {
                        size++;
                        upgrade = true;
                        start_food = false;
                        points += (5 * speed);
                    }
                    block [snake_x][snake_y] = char(254);
                    PRIORITY();
                    tail_x = snake_x;
                    tail_y = snake_y;
                    if (upgrade != true)
                    {
                        for (i = 0; i < size; i++)
                        {
                                if (block [tail_x + 1][tail_y] == char(254) && off != 2 && end_turn != true && pr_u == priority)
                                {
                                    tail_x += 1;
                                    off = 1;
                                    end_turn = true;
                                }
                                if (block [tail_x - 1][tail_y] == char(254) && off != 1 && end_turn != true && pr_d == priority)
                                {
                                    tail_x -= 1;
                                    off = 2;
                                    end_turn = true;
                                }
                                if (block [tail_x][tail_y - 1] == char(254) && off != 4 && end_turn != true && pr_r == priority)
                                {
                                    tail_y -= 1;
                                    off = 3;
                                    end_turn = true;
                                }
                                if (block [tail_x][tail_y + 1] == char(254) && off != 3 && end_turn != true && pr_l == priority)
                                {
                                    tail_y += 1;
                                    off = 4;
                                    end_turn = true;
                                }
                                if (end_turn != true)
                                {
                                    if (priority > 3)
                                    {
                                        priority = 1;
                                    }
                                    else
                                    {
                                        priority++;
                                    }
                                    i--;
                                }
                                end_turn = false;
                        }
                        off = 0;
                        block [tail_x][tail_y] = ' ';
                    }
                    cout<<"Points: "<<points;
                    upgrade = false;
                    Sleep(200 / speed);
                    system("cls");
                }
            }while (key != 'x' && end != true);
            if (end == true)
            {
                system("cls");
                cout<<"\n\n\n\n\t\t\t\tYOU LOSE!!!!\n\n\n\n\n";
                cout<<"\n\n\n\n\t\t\t\tyou did "<<points;
                cout<<" points \n\n\n";
                cout<<"press ENTER to continue...";
                system("pause > nul");
                system("cls");
            }
            if (key != 'x')
            {
                snake_x = 10, snake_y = 25, head_x = -1, head_y = 0, size = 3, off = 0, points = 0;
                end = false, upgrade = false, start_food = false, r = false, l = false, u = true, d = false;
            }
        }
        if (option == 2)
        {
            system("cls");
            cout<<"\n\n\n\nUse the buttons: 'w', 's', 'd', 'a', for up, down, right and left, respective.\n\n";
            cout<<"Click in 'x' for pause the game.\n\n";
            cout<<"Change the keys and the snake's speed in the menu, options.\n\n\n\n";
            cout<<"press ENTER to continue...";
            system("pause > nul");
            system("cls");
        }
        if (option == 3)
        {
            do
            {
                system("cls");
                cout<<"\n\n\n\nUse the keys '+' or '-' for change the snake's speed\n\n";
                cout<<"Use 'e' for edit the control. (just use characters)\n\n";
                cout<<"Press 'x' for exit of this options.\n\n";
                cout<<"Speed of Snake: "<<speed;
                if (kbhit())
                {
                    key2 = getch();
                    if (key2 == '+' && speed != 5)
                    {
                        speed++;
                    }
                    if (key2 == '-' && speed != 1)
                    {
                        speed--;
                    }
                    if (key2 == 'e')
                    {
                        cout<<"\nType the up key: ";
                        cin>>key_up;
                        cout<<"\nType the down key: ";
                        cin>>key_down;
                        cout<<"\nType the left key: ";
                        cin>>key_left;
                        cout<<"\nType the right key: ";
                        cin>>key_right;
                    }
                }
            }while (key2 != 'x');
            system("cls");
            key2 = 'o';
        }
    }while (option != 4);
    return 0;
}

void MAP()
{
    for (i = 0; i < com; i++)
    {
        printf("\t    ");
        for (j = 0; j < lar; j++)
        {
            printf("%c", block [i][j]);
        }
        printf("\n");
    }
}

void CONTROL()
{
    if (kbhit())
    {
        key = getch();
        if (key == key_up && d != true)
        {
            head_x = -1;
            head_y = 0;
            u = true;
            d = false;
            l = false;
            r = false;
        }
        if (key == key_down && u != true)
        {
            head_x = 1;
            head_y = 0;
            u = false;
            d = true;
            l = false;
            r = false;
        }
        if (key == key_left && r != true)
        {
            head_x = 0;
            head_y = -1;
            u = false;
            d = false;
            l = true;
            r = false;
        }
        if (key == key_right && l != true)
        {
            head_x = 0;
            head_y = 1;
            u = false;
            d = false;
            l = false;
            r = true;
        }
    }
}

void FOOD()
{
    srand(time(NULL));
    food_x = rand() % (com - 1);
    food_y = rand() % (lar - 1);
    while (block [food_x][food_y] == char(186) || block [food_x][food_y] == char(205) || block [food_x][food_y] == char(254))
    {
        food_x = rand() % (com - 1);
        food_y = rand() % (lar - 1);
    }
    if (start_food != true)
    {
        block [food_x][food_y] = '*';
        start_food = true;
    }
}

void PRIORITY()
{
    if (u == true)
    {
        priority = 1;
    }
    if (d == true)
    {
        priority = 2;
    }
    if (l == true)
    {
        priority = 3;
    }
    if (r == true)
    {
        priority = 4;
    }
}

quem puder me ajudar vlw aew

Link para o comentário
Compartilhar em outros sites

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152,2k
    • Posts
      652k
×
×
  • Criar Novo...