<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Samantha Hdez on Medium]]></title>
        <description><![CDATA[Stories by Samantha Hdez on Medium]]></description>
        <link>https://medium.com/@samanthahdez?source=rss-378be2db8767------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*SM__O8CAAkey1-uY.</url>
            <title>Stories by Samantha Hdez on Medium</title>
            <link>https://medium.com/@samanthahdez?source=rss-378be2db8767------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 22:25:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@samanthahdez/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Terran vs Zerg a PySC2 agent]]></title>
            <link>https://medium.com/@samanthahdez/terran-vs-zerg-a-pysc2-agent-f071b6c607fb?source=rss-378be2db8767------2</link>
            <guid isPermaLink="false">https://medium.com/p/f071b6c607fb</guid>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[starcraft]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Samantha Hdez]]></dc:creator>
            <pubDate>Mon, 23 Nov 2020 21:54:07 GMT</pubDate>
            <atom:updated>2020-11-23T22:00:41.752Z</atom:updated>
            <content:encoded><![CDATA[<p>by Samantha Hernández and Sergio Mercado</p><p>StarCraft is a military science fiction real-time strategy game, in this tutorial you will learn how two create a Zergs agent and a Torrens agent to make them fight.</p><p>For this tutorial you will need to install Python and PySC2 framework installed</p><ul><li><a href="https://www.python.org/downloads/">Download Python | Python.org</a></li><li><a href="https://pypi.org/project/PySC2/">PySC2 · PyPI</a></li></ul><h3>Libraries</h3><figure><img alt="Libraries" src="https://cdn-images-1.medium.com/max/743/1*PZ3g8_7R_32voPagqr5cZQ.png" /></figure><h3>Terran Agent</h3><p>For the Terran Agent we are going to generate 3 different structures</p><ul><li>Supply Depots</li><li>Barracks</li><li>Refineries</li></ul><p>And one type of unit</p><ul><li>Marines</li></ul><p>Since this agent will be fighting against Zerg, one of the easiest strategy is to attarck with a Marines rush</p><ol><li>Set up the class and environment</li></ol><p>In order to create any agent for StarCraft this step is required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*bBfgg2bhPuW8LQAru_iWJA.png" /></figure><p>2. Utility functions and Refinery function</p><p>This functions are useful no matter the type of agent you are creating</p><ul><li>unit_type_is_selected</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kJgorwrbRT4Ye9rUo6NsOw.png" /></figure><p>Useful to check if a type of unit is selected</p><ul><li>get_units_by_type</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*t0YgNiNOGOwgBEpg30vpVg.png" /></figure><p>This funtion returns a list with actual instances of the input unit</p><ul><li>can_do</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*DKD8jVyJzbAqZyI_ntNkQQ.png" /></figure><p>This function checks for the available actions</p><p>Create Refinery:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*fmgB9aMZ-G12Ww2weJYxUA.png" /></figure><p>Assign two SVCs to gather Verpene Gas:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*lF6wvGNZdV6PBI7MC7WQFQ.png" /></figure><p>3. Step</p><p>Inside the function step we are going to create all the strategy of our agent by creating units, structures etc</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HUOX9rhRsDEyR0-jW5hRnw.png" /></figure><p>First we generate an observation to find our current position and the position of the enemy (Zerg Agent)</p><p>Since we are going to generate a Marine rush and basics structures (Barracks, Refineries and Supply Depots) we just need to check for the mineral resource</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*V5MRPkny6zNCR1WMpToseQ.png" /></figure><p>We want a total of 3 Supply Depots:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*1kuiPHVMxPmTGrh5CXu01Q.png" /></figure><p>A total of 3 Barracks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*b2aaOUDcRVQHrhOb3jPW9A.png" /></figure><p>Two Refineries:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*L89IfqDdsAj-XNBEsqPoKw.png" /></figure><p>And we will train the Marines in group of 15 randomly in the Barracks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*e_4at1jPlsyM0JPGNbPhwQ.png" /></figure><p>To ATTACK we will send the marines in groups of 10 or more:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*KtoOJFB39PiR-JIxGUbipg.png" /></figure><p>SVC’s are the core units that recolect mineral (needes to create and train structures and units)</p><p>Here we are making them work (recolect):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*TC4ocPRbRZ3egXvJO_Ev6A.png" /></figure><p>Finally we just add this function in case any action is performed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*7LVibHZR1-_osh7C_goH9g.png" /></figure><h3>Zerg Agent</h3><p>For this agent a “Keep em coming” strategy is developed, yoy will notice that this is very different from the previous agent with more complex functions.</p><p>In this agent the supply rate is bigger than the attack rate</p><ol><li>Set up the class and environment</li></ol><p>In order to create any agent for StarCraft this step is required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*YYw14lmpp5ZoqtMF6qLaTQ.png" /></figure><p>2. Utility functions + Zerg building functions</p><p>This functions are useful no matter the type of agent you are creating</p><ul><li>unit_type_is_selected</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kJgorwrbRT4Ye9rUo6NsOw.png" /></figure><p>Useful to check if a type of unit is selected</p><ul><li>get_units_by_type</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*t0YgNiNOGOwgBEpg30vpVg.png" /></figure><p>This funtion returns a list with actual instances of the input unit</p><ul><li>can_do</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*DKD8jVyJzbAqZyI_ntNkQQ.png" /></figure><p>This function checks for the available actions</p><p>The next functions are used to simplify the code in the Step stage</p><p>Build Spawning Pools by transforming a dron:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*iD9qRAr--eJ2xiTacjMimw.png" /></figure><p>Build Roach Warrens1 Spawning Pool by transforming a dron:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*DjJrf0bXexjcpc08XftZ4w.png" /></figure><p>Build Infestation Pits by transforming a dron:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*pFfKVQE09KnVTNX9rWTg7Q.png" /></figure><p>Build Spires by transforming a dron:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*WG0_09QZ43W3dtYDNdoQCw.png" /></figure><p>This is the function that controls the structure creation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*kZH6hIavzLgFFm0pJcNGsA.png" /></figure><p>Build 2 extractors by transforming a dron when there is at least one available Vespene Geyser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*qp46zokQ9Bx9P4fsYZ3gMQ.png" /></figure><p>Gather Vespene Gas by transforming a dron (at least one extractor needs to be created) and assign 3 drones to recolect gas:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3RRw83JxwVQxnVK7axG-Xw.png" /></figure><p>Create units (Morph Overlors, Morph Drone, Morph Zergling, Morph Roach) and keep the Larvas working:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*lCjgoEv2oVHmyBWu53AfGA.png" /></figure><p>Attack in group of 5 or more Roaches and 15 or more Zerglings:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*kIkz9oqI1zuRaa_cDr2rYA.png" /></figure><p>Upgrade structures</p><p>Hatchery to Lair:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BnfizI8IFoqlyf5IaQp9_w.png" /></figure><p>Lair to Hive:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*fdk52JFHRFpXpGZnJxtgnw.png" /></figure><p>3. Step</p><p>Observe the number of minerals recolected:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*7HbStoyjMPTxFyGvE9qX0A.png" /></figure><p>Call attack sequence:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EDR_vlbo618wc3WmCL3-pQ.png" /></figure><p>Call the function to build a extractor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*Unh7Pfyi2or9FNM2OttBew.png" /></figure><p>Build a Spawning Pool a a Roach Warren:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*1TRjO3wE7D2pdMkmoXE0kQ.png" /></figure><p>Train to have in total 8 drones, more than 20 Zerglings and more than 5 Roaches:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*cDkeB8vk9SdRMTClZOWcCw.png" /></figure><p>Keep collecting the Vespene Gas with the drones and at least one Extractor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*vKsLXPeNT3J5zKlN5VR4kA.png" /></figure><p>Finally we just add this function in case any action is performed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*7LVibHZR1-_osh7C_goH9g.png" /></figure><h3>Terran vs Zerg set up</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*VDMCT4md1UsksYYRxx-8Zw.png" /></figure><ol><li>In order to fight both agents we need to create an object for each class (Terran and Zerg)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*LTFm2wevq9V3ES7l0b7Ndw.png" /></figure><p>2. Then with the While True statement we are going to make sure that the agents keep working until the game ends (one of them wins)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*sTd2JFT4Al_c1xnU9Xon7A.png" /></figure><p>3. We start the environment set up and we select the map</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*dnD4Ae0NuyBS0atGvLsW4g.png" /></figure><p>4. We define a list of players (Zerg and Terran)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*vS9qvDm0R1CiqOIRaT2t1w.png" /></figure><p>Commented in the code you can see an example of how to create a bot with is very easy difficulty level</p><p>5. We select the resolution for the screen (64/84)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*ywyNCRfXkje_v9HTnk-5lA.png" /></figure><p>6. Select the game speed in step_mul (Values from 16 to 22)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*3puZRR2usuA-9kSEvpgjrA.png" /></figure><p>7. In game_steps_per_episode we define the game lenght, if 0 the game will run until one of the agents (Terran/Zerg) wins</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*3puZRR2usuA-9kSEvpgjrA.png" /></figure><p>8. Because we want to see detail information while running the agents, we set up the visualize parameter to True</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*3puZRR2usuA-9kSEvpgjrA.png" /></figure><p>9. Finally we just call the main function, now</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*EnjJEzbXWcQTYduiLKW_-w.png" /></figure><h3><strong>Now, our agents are ready to fight!</strong></h3><p>You can find the complete code here:</p><p><a href="https://github.com/Prkizir/machine-learning/tree/master/"><strong>Prkizir/machine-learning (github.com)</strong></a></p><h3>Useful links (References):</h3><ul><li><a href="https://liquipedia.net/starcraft2/Terran_Units_(Legacy_of_the_Void)">Terran Units (Legacy of the Void) — Liquipedia — The StarCraft II Encyclopedia</a></li><li><a href="https://liquipedia.net/starcraft2/Zerg_Units_(Legacy_of_the_Void)">Zerg Units (Legacy of the Void) — Liquipedia — The StarCraft II Encyclopedia</a></li><li><a href="https://liquipedia.net/starcraft2/Protoss_Units_(Legacy_of_the_Void)">Protoss Units (Legacy of the Void) — Liquipedia — The StarCraft II Encyclopedia</a></li><li><a href="https://github.com/deepmind/pysc2/blob/master/pysc2/lib/units.py">pysc2/units.py at master · deepmind/pysc2 (github.com)</a></li><li><a href="https://github.com/deepmind/pysc2/blob/master/pysc2/lib/units.py">pysc2/units.py at master · deepmind/pysc2 (github.com)</a></li><li><a href="https://github.com/deepmind/pysc2/blob/master/pysc2/lib/actions.py">pysc2/actions.py at master · deepmind/pysc2 (github.com)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f071b6c607fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ciclos — Errores de compilación en C]]></title>
            <link>https://medium.com/@samanthahdez/ciclos-errores-de-compilaci%C3%B3n-en-c-9d5bc1807ac6?source=rss-378be2db8767------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d5bc1807ac6</guid>
            <dc:creator><![CDATA[Samantha Hdez]]></dc:creator>
            <pubDate>Wed, 15 Feb 2017 15:59:18 GMT</pubDate>
            <atom:updated>2017-03-01T17:47:26.581Z</atom:updated>
            <content:encoded><![CDATA[<p>Cuando programamos, hay veces que es necesario que una acción se ejecute más de una vez, es ahí en donde ocupamos los ciclos..</p><p>Hay 3 tipos de ciclos en C, con los tres podemos obtener el mismo resultado, pero siempre va a haber uno que se amolde más a nuestra necesidad y que haga el proceso de manera más sencilla.</p><h4>Ciclo For</h4><p>Es el de estructura condicional más definida, este tipo de ciclo es de gran utilidad cuando ya tenemos un número de repeticiones definidas, cuando sabemos que independientemente lo que se obtenga.</p><p>Su sintaxis es:</p><p>for (valor inicial ; condición ; aumento o disminución) { instrucciones a ejecutar}</p><p><em>Todo va con respecto a una misma variable</em></p><pre>for (ï=0;i&lt;3;i++){<br>   // Dentro de las llaves va todo el procedimiento que queramos que se repita   <br>}</pre><p><em>Ésto se lee como “para i igual con cero, mientras i sea menor que 3, i aumenta en uno” lo cual quiere decir que cada vez que el proceso se repita, i va a valer 1 más de lo que ya valía y que el código dentro del for se va a ejecutar 3 veces, pues los valores de i van a ir del 0 al 2 (para i menor que 3).</em></p><h4>Ciclo While</h4><p>Éste tipo de ciclo nos ofrece más libertad para programar, pues no cuenta con una estructura tan definida como el for, con while es suficiente poner la condición.</p><p>while (condición){</p><p>//código a ejecutar</p><p>}</p><pre>while (i&lt;5) {<br> y=y-1;<br> i=i+1;<br>}</pre><p><em>Ésto se lee como: mientras i sea menor que 5 el valor de y va a disminuir en uno y una vez que esto se ejecute i va a aumentar en 1.</em></p><p>Una ventaja de este ciclo es el uso de banderas, nosotros dentro de este podemos condicionar su resultado y en lugar que se repita 5 veces que sería el curso normal, hacer que se repita solo dos bajo cierta condición.</p><pre>#include&lt;stdio.h&gt;<br>#include&lt;stdlib.h&gt;</pre><pre>int main(){<br>    int y=0;<br>    int contador=0;<br>    while (contador==0){<br>        y=y+1;<br>        printf(&quot;%i&quot;, y);<br>        if (y==10){<br>            contador=1;<br>        }<br>    }<br>}</pre><p>Por ejemplo, en este ciclo tenemos inicializado la variable contador y la variable y en cero. La condición es que mientras contador sea igual con cero el valor de y va a aumentar en 1 y se va a imprimir… A simple vista tenemos un ciclo que se va a repetir de manera infinita, pero no. Sólo basta con que y, que inicialmente valía cero, llegué a 10 para que el valor de contador cambie a uno y no vuelva a entrar al ciclo.</p><h4>Ciclo Do While</h4><p>Es parecido al While sólo que éste se ejecuta al menos 1 vez sin importar cuál sea la condición, pues esta se encuentra al final de la estructura. Un uso común para los ciclos pueden ser los menús de opciones.</p><p>do{</p><p>//instrucciones a ejecutarse</p><p>}while (condición);</p><p>Otra diferencia con respecto a los dos ciclos anteriores, es que es la única estructura de ciclo que lleva punto y coma (;) después de la condición.</p><pre>do {<br>    printf(&quot; 1.Suma/n 2.Resta/n 3. Salir&quot;);<br>    scanf(&quot;%i%*c&quot;, &amp;opcion);<br>    switch (opcion){<br>    case 1:<br>        suma();<br>    break;<br>    case 2:<br>        resta():<br>    break;<br>    }while(opcion!=3);</pre><blockquote>Errores comunes — Ciclo infinito</blockquote><p>Es muy fácil confundir la condición, por eso es necesario recordar que se lee como “mientras que” en lugar de “hasta que”.</p><pre>#include&lt;stdio.h&gt;<br>#include&lt;stdlib.h&gt;</pre><pre>int main(){<br>    int y=0;<br>    int contador;<br>    for (contador=1;contador&gt;=0;contador++){<br>        y=y+2;<br>        printf(&quot;%i&quot;, y);<br>    }<br>}</pre><p>Podemos observar que tenemos para contador igual con 1, <strong>mientras que </strong>contador sea mayor que 0, contador va a aumentar en 1. Así que contador siempre entrará como verdadero en la condición, provocando que se impriman número pares infinitos.</p><blockquote>Asignar en lugar de comparar o viceversa</blockquote><p>Si programamos ésto y lo corremos, no nos saldrá un error como tal, pero si ignorará toda nuestra estructura, pues no está comparando nada.</p><p>Sólo le está asignando el valor de cero dos veces a la variable contador.</p><pre>#include&lt;stdio.h&gt;<br>#include&lt;stdlib.h&gt;</pre><pre>int main(){<br>    int y=0;<br>    int contador;<br>    for (contador=0;contador=0;contador++){<br>        y=y+2;<br>        printf(&quot;%i&quot;, y);<br>    }<br>}</pre><p>En el siguiente código sólo estamos comparando doble</p><pre>#include&lt;stdio.h&gt;<br>#include&lt;stdlib.h&gt;</pre><pre>int main(){<br>    int y=0;<br>    int contador;<br>    for (contador==0;contador==0;contador++){<br>        y=y+2;<br>        printf(&quot;%i&quot;, y);<br>    }<br>}</pre><p>Y obtenemos el mismo resultado, no se ejecuta el ciclo.</p><blockquote>Punto y coma después de la condición</blockquote><p><strong>Cabe aclarar que este error sólo es válido para la el for y el while, </strong>pues como se mencionó anteriormente el do while si lleva punto y coma (;) en su sintaxis.</p><pre>#include&lt;stdio.h&gt;<br>#include&lt;stdlib.h&gt;</pre><pre>int main(){<br>    int y=0;<br>    int contador;<br>    for (contador=0;contador&lt;10;contador++);{<br>        y=y+2;<br>        printf(&quot;%i&quot;, y);<br>    }<br>}</pre><p>Recordando un poco, obtendremos el mismo resultado de ponerle un punto y coma a un if o un switch, se ignorará el ciclo pues lo que hace el compilador es que toma como instrucción lo que está entre la condición y el punto y coma.</p><blockquote>Omitir punto y coma en el do while</blockquote><p>Así como poner un punto y coma después de la condición en un for y/o while es un error, también lo es omitirlo después de la condición de un do While.</p><pre>#include&lt;stdio.h&gt;<br>#include&lt;stdlib.h&gt;</pre><pre>int main(){<br>    int opcion;<br>    int n1=5;<br>    int n2=3;<br>do {<br>    printf(&quot; 1.Suma/n 2.Resta/n 3. Salir&quot;);<br>    scanf(&quot;%i%*c&quot;, &amp;opcion);<br>    switch (opcion){<br>    case 1:<br>        printf(&quot;%i&quot;,n1+n2);<br>    break;<br>    case 2:<br>        printf(&quot;%i&quot;,n1+n2);<br>    break;<br>    }while(opcion!=3)<br>}<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d5bc1807ac6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Errores comunes en funciones y procedimientos en C]]></title>
            <link>https://medium.com/@samanthahdez/errores-comunes-en-funciones-y-procedimientos-en-c-c650f9b9ca33?source=rss-378be2db8767------2</link>
            <guid isPermaLink="false">https://medium.com/p/c650f9b9ca33</guid>
            <dc:creator><![CDATA[Samantha Hdez]]></dc:creator>
            <pubDate>Wed, 15 Feb 2017 14:09:13 GMT</pubDate>
            <atom:updated>2017-02-15T14:09:13.015Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Función.- Es un conjunto de líneas de código, a las cuales se les pueden pasar valores como parámetros y su objetivo principal es regresar un valor</em>.</p><p>Tienen una sintaxis muy particular, que si no es seguida al pie de la letra, no obtendremos el resultado deseado.</p><blockquote>No pasar bien los parámetros</blockquote><pre>#include&lt;stdio.h&gt;<br>#include&lt;stdlib.h&gt;</pre><pre>int suma(numero 1, numero 2){<br>    int resultado;<br>    resultado=numero1+numero2;<br>    return resultado;<br>}</pre><pre>int main(){<br>    int numero1;<br>    int numero 2;<br>    printf(&quot;Numero 1: &quot;);<br>    scanf(&quot;%i%*c&quot;, &amp;numero1);<br>    printf(&quot;Numero 2: &quot;);<br>    scanf(&quot;%i%*c&quot;, &amp;numero2);<br>    printf(&quot;La suma es: %i&quot;, suma(numero1,numero2));<br><em>}</em></pre><p><em>En este caso, los parámetros correctos deberían ser (int numero1, int numero2). También se observa que no marca error y al parecer el programa corre de manera normal, el problema es cuando se tienen más funciones, pues puede que empiecen a surgir problemas.</em></p><p>Recordando, cuando creamos una función y queremos pasarle parámetros necesitamos indicar qué tipo de variable es.</p><p>Claro, esta especificación va sólo en la misma función, cuando se manda “llamar” sólo se introduce el nombre de la variable.</p><pre>#include&lt;stdio.h&gt;<br>#include&lt;stdlib.h&gt;</pre><pre>int suma(numero 1, numero 2){<br>    int resultado;<br>    resultado=numero1+numero2;<br>    return resultado;<br>}</pre><pre>int main(){<br>    int numero1;<br>    int numero 2;<br>    printf(&quot;Numero 1: &quot;);<br>    scanf(&quot;%i%*c&quot;, &amp;numero1);<br>    printf(&quot;Numero 2: &quot;);<br>    scanf(&quot;%i%*c&quot;, &amp;numero2);<br>    printf(&quot;La suma es: %i&quot;, suma(int numero1, int numero2));<br>}</pre><p><em>Se observa un error debido a que la función está siendo llamada de manera incorrecta.</em></p><blockquote>Regresar más de un valor</blockquote><p>En el siguiente ejemplo podemos analizar que la función “suma” contiene dos variables, “resultado” que almacena el valor de “numero1&quot; y “numero2&quot; y “x” que almacena la sustracción de los dos valores.</p><pre>#include&lt;stdio.h&gt;<br>#include&lt;stdlib.h&gt;</pre><pre>int suma(int numero 1, int numero 2){<br>    int resultado;<br>    resultado=numero1+numero2;<br>    int x;<br>    x=numero1-numero2;<br>    return resultado;<br>    rsturn x;<br>}</pre><pre>int main(){<br>    int numero1;<br>    int numero 2;<br>    printf(&quot;Numero 1: &quot;);<br>    scanf(&quot;%i%*c&quot;, &amp;numero1);<br>    printf(&quot;Numero 2: &quot;);<br>    scanf(&quot;%i%*c&quot;, &amp;numero2);<br>    printf(&quot;La suma es: %i&quot;, suma(numero1, numero2));<br>}\<br></pre><p>A veces podemos llegar a confundirnos y tendemos a querer regresar más de un valor por función, lo cuál obviamente no sucederá.</p><p>Cuando tenemos más de un return por función, el programa tomará sólo la primera.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*WAjJwk63YqGnmN1X0_VMOA.png" /><figcaption>El primer return fue el de resultado (variable que almacenaba el valor de numero1 más numero2)</figcaption></figure><blockquote>No regresar un valor</blockquote><p>Si bien el objetivo de una función es regresar un valor, puede que lo omitamos a la hora de programar..</p><pre>#include&lt;stdio.h&gt;<br>#include&lt;stdlib.h&gt;</pre><pre>int suma(int numero 1, int numero 2){<br>    int resultado;<br>    resultado=numero1+numero2;<br>    int x;<br>    x=numero1-numero2;<br>   <br>}</pre><pre>int main(){<br>    int numero1;<br>    int numero 2;<br>    printf(&quot;Numero 1: &quot;);<br>    scanf(&quot;%i%*c&quot;, &amp;numero1);<br>    printf(&quot;Numero 2: &quot;);<br>    scanf(&quot;%i%*c&quot;, &amp;numero2);<br>    printf(&quot;La suma es: %i&quot;, suma(numero1, numero2));<br>}</pre><p>En la imagen podemos percatarnos que la función recibe como parámetro dos números enteros (dados por el usuario).</p><p>En la variable “resultado” estos se suman y en la variable “x” se restan, pero hay que recordar que una función sólo regresa 1 valor, en otras palabras, cuando omitimos el return, lo que nos regresará es el resultado de la última operación, en este caso “x” que es la resta de los dos números.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*qRp0dAHBlGib831tC3eFTg.png" /></figure><blockquote>No declarar bien el tipo de función</blockquote><p>Es importante tener presente que el tipo de función depende del tipo de dato que se desea regresar..</p><p>Por ejemplo si queremos una función que regrese el resultado de la división de dos números lo más conveniente sería una función “float” ya que muchas divisiones no son exactas.</p><pre>#include&lt;stdio.h&gt;<br>#include&lt;stdlib.h&gt;</pre><pre>float suma(int numero 1, int numero 2){<br>    int resultado;<br>    resultado=numero1+numero2;<br>    int x;<br>    x=numero1-numero2;<br>    return resultado;<br>   <br>}</pre><pre>int main(){<br>    int numero1;<br>    int numero 2;<br>    printf(&quot;Numero 1: &quot;);<br>    scanf(&quot;%i%*c&quot;, &amp;numero1);<br>    printf(&quot;Numero 2: &quot;);<br>    scanf(&quot;%i%*c&quot;, &amp;numero2);<br>    printf(&quot;La suma es: %i&quot;, suma(numero1, numero2));<br>}</pre><p>En la imagen anterior la función es de tipo “float” y el valora regresar es el de ”resultado” que está declarada como “int” dentro de la misma.</p><p>Cuando se imprime la función el tipo de dato está dado como “int”, debido a esto cuando corramos el programa lo único que obtendremos es un 0.</p><p>En este caso tenemos dos alternativas, podemos cambiar el tipo de función a int para que coincida con la variable y el tipo de dato a imprimir, o podemos cambiar éstos a “float” para que toso quede dado en decimales.</p><p><strong><em>Para resumir, un ejemplo de una función correcta:</em></strong></p><pre>#include&lt;stdio.h&gt;<br>#include&lt;stdlib.h&gt;</pre><pre>int suma(int numero 1, int numero 2){<br>    int resultado;<br>    resultado=numero1+numero2;<br>    int x;<br>    x=numero1-numero2;<br>    return resultado;<br>   <br>}</pre><pre>int main(){<br>    int numero1;<br>    int numero 2;<br>    printf(&quot;Numero 1: &quot;);<br>    scanf(&quot;%i%*c&quot;, &amp;numero1);<br>    printf(&quot;Numero 2: &quot;);<br>    scanf(&quot;%i%*c&quot;, &amp;numero2);<br>    printf(&quot;La suma es: %i&quot;, suma(numero1, numero2));<br>}</pre><p>Procedimiento.- Conjunto de código o subrutina que realiza una tarea especifica, a diferencia de la función, los procedimientos no regresan ningún valor.</p><p>Cuando tenemos funciones y/o procedimientos, éstos siempre tienen que estar arriba del main, si no, un error como estos podría aparecer…</p><pre>#include&lt;stdio.h&gt;<br>#include&lt;stdlib.h&gt;</pre><pre>int main(){<br>    pedir_valores();<br>    }<br>    <br>int suma(int numero 1, int numero 2){<br>    int resultado;<br>    resultado=numero1+numero2;<br>    int x;<br>    x=numero1-numero2;<br>    return resultado;<br>    }</pre><pre>void pedir_valores(){<br>    int numero 1;<br>    int numero 2;<br>    printf(&quot;Numero 1: &quot;);<br>    scanf(&quot;%i%*c&quot;, &amp;numero1);<br>    printf(&quot;Numero 2: &quot;);<br>    scanf(&quot;%i%*c&quot;, &amp;numero2);<br>    printf(&quot;La suma es: %i&quot;,suma(numero1, numero2));<br>    }</pre><p>Aquí un ejemplo de un programa con funciones y procedimientos bien elaborados..</p><pre>#include&lt;stdio.h&gt;<br>#include&lt;stdlib.h&gt;<br>    <br>int suma(int numero 1, int numero 2){<br>    int resultado;<br>    resultado=numero1+numero2;<br>    int x;<br>    x=numero1-numero2;<br>    return resultado;<br>    }</pre><pre>void pedir_valores(){<br>    int numero 1;<br>    int numero 2;<br>    printf(&quot;Numero 1: &quot;);<br>    scanf(&quot;%i%*c&quot;, &amp;numero1);<br>    printf(&quot;Numero 2: &quot;);<br>    scanf(&quot;%i%*c&quot;, &amp;numero2);<br>    printf(&quot;La suma es: %i&quot;,suma(numero1, numero2));<br>    }</pre><pre>int main(){<br>    pedir_valores();<br>    }</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c650f9b9ca33" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Errores de compilación If y switch]]></title>
            <link>https://medium.com/@samanthahdez/errores-de-compilaci%C3%B3n-if-y-switch-3ffc1c5eeea?source=rss-378be2db8767------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ffc1c5eeea</guid>
            <dc:creator><![CDATA[Samantha Hdez]]></dc:creator>
            <pubDate>Wed, 15 Feb 2017 13:46:11 GMT</pubDate>
            <atom:updated>2017-02-15T13:46:11.572Z</atom:updated>
            <content:encoded><![CDATA[<p>Éstas estructuras nos permiten condicionar un programa, es decir, que sólo se haga una porción de código.</p><blockquote>Errores comunes en el if</blockquote><p><strong><em>Poner punto y coma después de la comparación</em></strong></p><p>Estás haciendo un programa, que necesita de una comparación, lo corres pero parece ser que la condición no entra…</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;</pre><pre>int main(){<br>    int y=45;<br>    int i=l;<br>    if (i==0);{<br>        printf(&quot;%i&quot;,y);<br>    }<br>}</pre><p><em>En este programa, lo que inicialmente se busca es comparar si i vale 0, si esta condición resulta verdadera, se imprimirá el valor de y. Pero, debido al punto y coma, aunque i vale 1, se imprimirá el valor de y.</em></p><p>Éste error se debe a que al momento de poner un punto y coma ; después de la comparación, todo lo que queda después no entra en la condición.</p><p>El programa toma como instrucción lo que está entre la condición y el punto y coma, y si no hay nada entre éstos dos, seguirá con las instrucciones que se encuentren debajo de ésta.</p><h4><strong><em>Comparar mal</em></strong></h4><p>Un error muy frecuente que cometemos a la hora de programar, es asignar en lugar de comparar.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;</pre><pre>int main(){<br>    int y=45;<br>    int i=2;<br>    if (i=1){<br>        printf(&quot;%i&quot;,y);<br>    }<br>}</pre><p><em>En este caso, aunque i valga 2 se imprimirá el valor de y, haciendo caso omiso de la comparación.</em></p><p>Asignar es darle un valor a una variable, esto se hace con un sólo igual =, mientras que la comparación lleva doble igual ==</p><p>Cuando en un if ponemos una asignación en lugar de unas comparación lo que hará el programa, igual que con el punto y coma, es omitir la estructura.</p><p>En la siguiente imagen podrás observar cómo se hace uso correcto de un if.</p><pre>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;</pre><pre>int main(){<br>    int y=45;<br>    int i=2;<br>    if (i==1){<br>        printf(&quot;%i&quot;,y);<br>    }<br></pre><blockquote>Errores en el switch</blockquote><h4><em>No poner las llaves después de iniciar el switch</em></h4><p>Es importante recordar la estructura, pues si cometemos este error, el programa ni siquiera va a correr</p><p>switch (variable)</p><p>{</p><p>}</p><pre>#include&lt;stdio.h&gt;<br>#include&lt;stdlib.h&gt;</pre><pre>int main(){<br>    int opcion;<br>    int n1=5;<br>    int n2=6;<br>    int resultado;<br>    printf(&quot;1.Suma \n2.Resta \n3.Multiplicacion \nOpcion: &quot;);<br>    scanf(&quot;%i%*c&quot;, &amp;opcion);<br>    switch (opcion)<br>    case 1:<br>        resultado=n1+n2;<br>        break;<br>    case 2:<br>        resultado=n1-n2;<br>        break;<br>    case 3:<br>        resultado=n1*n2;<br>        break;<br>        printf(&quot;%i&quot;, resultado);<br>}</pre><p><em>El error no lo marca inmediatamente después de que se omiten las llaves, lo marca dentro de los case´s</em></p><h4><em>Uso incorrecto de case’s</em></h4><p>El switch funciona con todos los tipos de variables y esta diferencia se tiene que poner en los case´s a la hora de comparar.</p><p>Por ejemplo cuando tenemos un switch de números enteros es suficiente con poner case 1:</p><p>Cuando es un dato tipo char.. case ‘a’:</p><p>Para un String.. case “hola”:</p><p>Si omitimos alguna de estas diferencias y lo ponemos de manera incorrecta el programa si correrá, pero ignorara todo lo que esté dentro del switch..</p><pre>#include&lt;stdio.h&gt;<br>#include&lt;stdlib.h&gt;</pre><pre>int main(){<br>    int opcion;<br>    int n1=5;<br>    int n2=6;<br>    int resultado;<br>    printf(&quot;1.Suma \n2.Resta \n3.Multiplicacion \nOpcion: &quot;);<br>    scanf(&quot;%i%*c&quot;, &amp;opcion);<br>    switch (opcion){<br>    case &#39;1&#39;:<br>        resultado=n1+n2;<br>        break;<br>    case &#39;2&#39;:<br>        resultado=n1-n2;<br>        break;<br>    case &#39;3&#39;:<br>        resultado=n1*n2;<br>        break;<br>        printf(&quot;%i&quot;, resultado);<br>    }<br>}</pre><p><em>En este caso se está usando un switch entero, pero se está comparando como si fuera char…</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*o6GfRhzBNf99-JX9yE6vhA.png" /></figure><p>Corriendo el ejemplo anterior obtenemos que la suma de 5+9=69 esto es debido a que se ignora el switch.</p><p>Finalmente, un ejemplo de un uso correcto del switch:</p><pre>#include&lt;stdio.h&gt;<br>#include&lt;stdlib.h&gt;</pre><pre>int main(){<br>    int opcion;<br>    int n1=5;<br>    int n2=6;<br>    int resultado;<br>    printf(&quot;1.Suma \n2.Resta \n3.Multiplicacion \nOpcion: &quot;);<br>    scanf(&quot;%i%*c&quot;, &amp;opcion);<br>    switch (opcion){<br>    case 1:<br>        resultado=n1+n2;<br>        break;<br>    case 2:<br>        resultado=n1-n2;<br>        break;<br>    case 3:<br>        resultado=n1*n2;<br>        break;<br>        printf(&quot;%i&quot;, resultado);<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ffc1c5eeea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Errores de compilación en C]]></title>
            <link>https://medium.com/@samanthahdez/errores-de-compilaci%C3%B3n-en-c-6c84c8557cd3?source=rss-378be2db8767------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c84c8557cd3</guid>
            <dc:creator><![CDATA[Samantha Hdez]]></dc:creator>
            <pubDate>Wed, 01 Feb 2017 17:45:04 GMT</pubDate>
            <atom:updated>2017-02-01T17:45:04.545Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Errores comunes declarando el main.</blockquote><p><strong><em>Omitir los paréntesis.</em></strong></p><p>Como se puede ver en la imagen superior, el error que describe el compilador realmente no da referencia a la omisión, por lo cual puede llegar a ser un tanto difícil detectarlo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f4gTgTwviXl6TBfiTMwmIA.png" /><figcaption>error: expected ‘ = ’ , ‘ , ’ , ‘ ; ‘ , ‘ asm ‘ or ‘ __attribute__ ’ before ‘ { ‘ token</figcaption></figure><p><strong><em>Cerrar llave sin abrirla</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5d9f2UDomHWnw99tfJz5jQ.png" /></figure><p>Nuevamente, el programa no nos da una pista concreta del símbolo que estamos omitiendo.</p><p><strong><em>Abrir llave y no cerrarla</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fgi-wVJf4jGLR5c4l8teDQ.png" /><figcaption>error: expected identifier or ‘ { ‘ before ‘ } ‘ token</figcaption></figure><p>En este caso el compilador SI nos dice claramente cuál es nuestro error, cabe recordar que el número de llaves { abiertas, tiene que ser igual al número de llaves cerradas } .</p><p>A continuación se muestra la sintaxis correcta de un main:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*AGu6r_7dFGtLDSHlkWlhiA.png" /></figure><blockquote>Librerías</blockquote><p><strong><em>Omitir la librería &lt;stdio.h&gt;</em></strong></p><p>Más que un error de compilación, es una advertencia de omisión, como se puede ver en la siguiente imagen, el programa no marca error, pero marca que algunas de las operaciones que se están realizando son “incompatibles”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cXXCYpVTuFQrEaQkxKKkNA.png" /><figcaption>warning: incompatible implicit declaration of built-in function ‘printf’</figcaption></figure><p>En el siguiente link se enlistan las funciones que contiene la librería &lt;stdio.h&gt;</p><p><a href="https://es.wikipedia.org/wiki/Stdio.h">stdio.h - Wikipedia, la enciclopedia libre</a></p><p>Otra librería importante es &lt;stdlib.h&gt;</p><p><a href="https://es.wikipedia.org/wiki/Stdlib.h">stdlib.h - Wikipedia, la enciclopedia libre</a></p><blockquote>Errores comunes en el if</blockquote><p><strong><em>Poner punto y coma después de la comparación</em></strong></p><p>Estás haciendo un programa, que necesita de una comparación, lo corres pero parece ser que la condición no entra…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*UUGcUFA6yDzRgRDsInwUvw.png" /><figcaption>En este programa, lo que inicialmente se busca es comparar si i vale 0, si esta condición resulta verdadera, se imprimirá el valor de y. Pero, debido al punto y coma, aunque i vale 1, se imprimirá el valor de y.</figcaption></figure><p>Éste error se debe a que al momento de poner un punto y coma ; después de la comparación, todo lo que queda después no entra en la condición.</p><p>El programa toma como instrucción lo que está entre la condición y el punto y coma, y si no hay nada entre éstos dos, seguirá con las instrucciones que se encuentren debajo de ésta.</p><p><strong><em>Comparar mal</em></strong></p><p>Un error muy frecuente que cometemos a la hora de programar, es asignar en lugar de comparar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*WQ9WVILLxdM5jnUZ1vykug.png" /><figcaption>En este caso, aunque i valga 2 se imprimirá el valor de y, haciendo caso omiso de la comparación.</figcaption></figure><p>Asignar es darle un valor a una variable, esto se hace con un sólo igual =, mientras que la comparación lleva doble igual ==</p><p>Cuando en un if ponemos una asignación en lugar de unas comparación lo que hará el programa, igual que con el punto y coma, es omitir la estructura.</p><p>En la siguiente imagen podrás observar cómo se hace uso correcto de un if.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*Dgcyv_zyJ1YuaaXizrMLxA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c84c8557cd3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>