gpt4 book ai didi

c++ - 第一个数和第二个数之间可同时被 4 和 6 整除的所有整数之和

转载 作者:太空宇宙 更新时间:2023-11-04 14:59:41 27 4
gpt4 key购买 nike

我需要编写一个程序来获取 2 个整数。然后程序将显示两个数字之间可同时被 4 和 6 整除的所有整数的总和

我尝试执行下面的代码:

#include <iostream>
using namespace std;

int main()
{
int num1, num2, sum=0;

cout << "Input first number : ";
cin >> num1;
cout << "Input second number : ";
cin >> num2;


for(int i = num1 + 1;i<num2;i++)
{
if ( num1 % 4 == 0 && num2 % 6 == 0)
{
sum = sum + i;
}
}
cout<< "The sum of all integers that are both divisible by 4 and 6 between " << num1 << " and " << num2 << " is " << sum << endl;
system("pause");
return 0;
}

我的预期结果应该是

输入第一个数字:4
输入第二个数字:12
4和12之间所有能被4和6整除的整数之和是12“因为 12 是唯一可以同时被 4 和 6 整除的数字”

但实际结果是
输入第一个数字:4
输入第二个数字:12
4和12之间所有能被4和6整除的整数之和是56

最佳答案

这是正确的程序:

#include <iostream>
using namespace std;

int main()
{
int num1, num2, sum=0;

cout << "Input first number : ";
cin >> num1;
cout << "Input second number : ";
cin >> num2;


for(int i = num1;i<=num2;i++) // if you want to include num1 and num2
//for(int i = num1+1;i<num2;i++) // if you do not want to include num1 and num2
{
if ( i % 4 == 0 && i % 6 == 0)
{
sum = sum + i;

}
}
cout<< "The sum of all integers that are both divisible by 4 and 6 between " << num1 << " and " << num2 << " is " << sum << endl;
system("pause");
return 0;
}

关于c++ - 第一个数和第二个数之间可同时被 4 和 6 整除的所有整数之和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55590465/

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