Hello, i was doing a simple problem, but i got into some trouble with a function.Here is the source code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include<iostream>
#include<math.h>
usingnamespace std;
int prim(int m);
int main(){
int i,n,x,nr=0;
cout<<"n=";cin>>n;
for(i=0;i<n;i++){
cout<<"x["<<i<<"]=";cin>>x;
if(prim(x)==1) nr++;}
cout<<endl<<"nr="<<nr;
return 0;}
int prim(int m){
int i;
float n;
n=sqrt(m);
for(i=0;i<=n;i++){
if(m%i==0) return 1;}
return 0;}
It's a logycal error, but i simply can't find it...when i run it tells me "Floating point exeption"...why?
PS: The "prim" function is supposed to return 1 if a number is prime, and 0 if it's not.Somewone please help me, lol, i know it's simple, but i simply can't find the mistake...
Your code would be much easier to read if you didn't try to cram multiple things on one line. Don't be afraid of whitespace. A few empty lines and spaces go a long way with code readability.
Anyway your problem is here:
1 2
for(i=0;i<=n;i++){
if(m%i==0) return 1;}
i starts at zero.
m%i effectively does division
therefore you're dividing by zero, which will make your program explode.
lol, noob mistake :P thanks a lot :)
And about the writing, i simply can't read the "loose" code:P i mean, i don't get the encapsulation if it's not cramped.Usualy i use indent ( a verry useful tool, for guys that write ugly) :)
Thanks a lot :)
PS: By the way, you know somekind of ebook or something, that will help me interpret errors? I'm using Code::Blocks 8.02 on Ubuntu 10.04
// I hope that cramped style works out for you and others, because I always seem to hear complaints about code readability from the authors of the books I read lol.
// And whatcha mean by you don't get the "encapsulation" if it's not cramped? Isn't that about restricting access to an object's components? Orr are you talking about scope, as in the '}' and '{'? Well if it's the scope then why not put the curly braces on their own lines and then you'd be able to line up the braces and tell what's nested in what using the magical indentation? Unless I'm way off on what you're talking about ^.^