如何在 c++ 中循环获取奇数整数的总和

How to get the sum of odd integers in loop in c++

本文关键字:整数 获取 c++ 循环      更新时间:2023-10-16

伙计们,我正在尝试输出a和b之间所有奇数的总和。尽管给定了条件,但输出的数字总会小于"a"。

#include <iostream>
#include <string>
int main()
{
int a =0;
int b =0;
int c=0;
std:: cout <<"Enter a number: n";
std::cin >> a;
std:: cout <<"Enter a number: n";
std::cin >> b;
int sum=0;
for(c; c%2!=0, c >= a, c <=b ; c+=2)
{
    std::cout << "This is one of the odd numbers between " << a << " and " << b << " : "<< c << std::endl;
    sum +=c;
}
std::cout << "The sum is : " <<sum;
return 3;
}

用试试这个

for(c=a; c%2!=0 && c>= a && c <=b ; c++){ std::cout <<"这是 " <<a <<" 和 " <<b <<之间的奇数之一 " : "<<c <<std::endl; 总和 +=c;}