Jump to content
Incepat0r

Problema ciudata C

Recommended Posts

Am urmatorul cod in C:


#include <stdio.h>
int main()
{
int r,a=-3,b=7,c=9,d=2,e=11,f=1,g=77;
r=(a*b*c+d*e*f)%g;
printf("%d",r);
return 0;
}

Rulat in Code Blocks 13.12 si compilatorul implicit MinGW, dar si aici: Compile and Execute C online si rezultatul este -13

Scris in google: (-3*7*9+2*11*1) mod 77 si rezultatul este 64: https://www.google.ro/#q=%28-3*7*9%2B2*11*1%29+mod+77

Acum stiu sigur ca rezultatul corect este cel indicat de google adica 64, nelamurirea mea este cum pot corecta aceasta eroare in C ca mi-a luat 2 ore sa descopar acest mic bug intr-un cod de peste 1K linii.

Link to comment
Share on other sites

  • Active Members

(a*b*c+d*e*f)%g = (-3*7*9 + 2*11*1)%77=(-189+22)%77 = (-167) % 77 = 2 rest -13.

Code Blocks are dreptate;

% este functia "modulo" in C/C++/etc - adica restul impartirii lui 77 la -189 care evident este -13 :)

Edited by MrGrj
Link to comment
Share on other sites

In ambele cazuri modulul este corect. Modulul unui numar este restul impartirii.

Atunci cand modulul iti da un numar negativ, e posibilitatea de a transforma acel numar negativ in numar pozitiv cu formula: restul = restul + impartitorul

Google face singur aceasta transformare si transforma numarul -13 in numar pozitiv, fiind 77-13=64. C nu face acest lucru de la sine, dar o poti face tu adaugand cateva linii de cod pentru cazul in care restul e negativ.

Un alt exemplu fiind -8%5=-3=5-3=2

Poti face asta de mana cu matematica de clasa 12 unde inveti modulul unui numar.

In concluzie, poti adauga acolo linia asta inainte de printf:


if(r < 0)
r = r+g;

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...