Incepat0r Posted May 27, 2014 Report Share Posted May 27, 2014 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 -13Scris 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+77Acum 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. Quote Link to comment Share on other sites More sharing options...
Active Members MrGrj Posted May 27, 2014 Active Members Report Share Posted May 27, 2014 (edited) (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 May 27, 2014 by MrGrj Quote Link to comment Share on other sites More sharing options...
Incepat0r Posted May 28, 2014 Author Report Share Posted May 28, 2014 Problema este ca pentru numere negative se calculeaza modulul altfel: https://answers.yahoo.com/question/index?qid=20080922034737AAsFEfYDeci C sucks si la operatii elementare..... Quote Link to comment Share on other sites More sharing options...
nedo Posted May 28, 2014 Report Share Posted May 28, 2014 Calculeaza modulul tu, de mana, ai sa observi ca ceea ce MrGrj a scris respecta exact ceea ce este scris in link-ul ala pe care l-ai dat. ca si chestie -167 % 77 = 2 rest -13 deoarece 77* 2 = 154 si -167 + 154 = -13. Quote Link to comment Share on other sites More sharing options...
Khronos Posted May 28, 2014 Report Share Posted May 28, 2014 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 + impartitorulGoogle 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=2Poti 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; Quote Link to comment Share on other sites More sharing options...