gpt4 book ai didi

C++ : Count even/odd numbers in a range

转载 作者:行者123 更新时间:2023-11-30 01:07:46 24 4
gpt4 key购买 nike

我的程序必须计算一个范围内有多少数字是偶数,有多少是奇数,但我似乎无法弄清楚。它有点管用但是当我把数字放进去时,它就会胡说八道。在编程方面我是一个极端的菜鸟,我认为问题必须在第 21 行 for (i=n; i<=m; i++) { ?但我不确定。我有一本编程书,但用处不大,也许有人可以帮忙?

#include <iostream>

using namespace std;

int main()
{
int n;
int m;
int i;
int a;
int b;

cout << "Enter a number that begins interval: ";
cin >> n;
cout << "Enter a number that ends interval: ";
cin >> m;
a=0;
b=0;


for (i=n; i<=m; i++) {
if (i%2 == 0){
a=a+i;
}
else {
b=b+i;
}
}
cout << " unequal numbers: " << a << endl;
cout << " equal numbers: " << b << endl;

最佳答案

假设您指的是偶数和奇数,您的问题出在这段代码中:

for (i=n; i<=m; i++) {
if (i%2 == 0){
a=a+i; // increase number of even numbers by i
}
else {
b=b+i; // increase number of odd numbers by i
}
}

你可能想要做的是加 1(而不是 i 是什么):

 for (i = n; i <= m; ++i) {
if (i % 2 == 0)
++a; // increase number of even numbers by one
else
++b; // increase number of odd numbers by one
}

我还建议使用更好的变量名,例如 even 和 odd 而不是 a 和 b 等等。它使每个人(甚至您)都更容易理解代码。

再多一点提示。好的做法是在声明变量后立即分配变量:

int m = 0;

您可以在 for 循环内声明变量,在您的情况下无需在循环外声明它:

for (int i = n; i <= m; ++i) { ... }

示例它如何改变代码的外观和清晰度:

#include <iostream>

using namespace std;

int main() {
int from = 0,
to = 0,
even = 0,
odd = 0;

cout << "Enter a number that begins interval: ";
cin >> from;

cout << "Enter a number that ends interval: ";
cin >> to;

for (int i = from; i <= to; ++i) {
if (i % 2 == 0)
++even;
else
++odd;
}

cout << " even numbers: " << even << endl;
cout << " odd numbers: " << odd << endl;

return 0; // don't forget this! main is function returning int so it should return something
}

关于C++ : Count even/odd numbers in a range,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43833359/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com