What is wrong with my C program?
From: Hoffmann (oasf2004_at_yahoo.com)
Date: 03/26/05
- Next message: Mark P: "Re: What is wrong with my C program?"
- Previous message: Eric A. Johnson: "Use of new and delete in C++"
- Next in thread: Mark P: "Re: What is wrong with my C program?"
- Reply: Mark P: "Re: What is wrong with my C program?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: 25 Mar 2005 17:12:20 -0800
Dear All,
I am trying to write a C program that asks the user to supply three
integers k, m, and n. Then, the program computes the sum of all the
integers between m and n that are divisible by k. I just wrote the
following program, so. [Please, see below]. However, I am getting a
wrong output. I mean, I am getting a number higher than the expected
one. For instance, if I enter k = 2, m = 4, and n = 10, the sum of the
numbers between m (= 4) and n (= 10), that are divisible by k (= 2)
would be 14 (= 6 + 8). However, I am getting 18, instead.
Could you, please, help me to fix this program?
Thanks!
Hoffmann
#include <stdio.h>
int main()
{
int k, m, n, //The three integers
n2, //Numbers between m and n
sum = 0; //Sum of the numbers
printf("Input three integers: ");
scanf("%d%d%d", &k, &m, &n);
if (k > 1) {
for (n2 = m; n2 < n; ++n2) { //Numbers between m and n
if (n2 % k == 0)
sum += n2;
}
printf("You entered the integers k = %d, m = %d, and n =
%d.\n", k, m, n);
printf("The sum of all integers between m and n that are
divisible"\
" by k is %d.\n", sum);
}
getch();
return 0;
}
- Next message: Mark P: "Re: What is wrong with my C program?"
- Previous message: Eric A. Johnson: "Use of new and delete in C++"
- Next in thread: Mark P: "Re: What is wrong with my C program?"
- Reply: Mark P: "Re: What is wrong with my C program?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|