我有一个绘制10个数字的代码,我需要计算非零数字的总和与乘积,并显示已相乘的数字。我已经有了大部分代码,但是我不知道如何将非零数字相乘然后显示它们。有人可以帮我吗?
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <windows.h>
using namespace std;
int main()
{
cout << "draws 10 numbers:" << endl;
Sleep(1000);
cout << endl;
srand(time(0));
int sum=0;
int product=1;
for(int i=0,value=0;i<10;i++,sum+=value,product*=value)
{
{
value = rand()%10+0;
Sleep(1000);
cout << value << endl;
}
}
Sleep(1000);
cout<<"the sum is "<< sum <<endl;
cout <<"the product is "<< product <<endl;
return 0;
}
如果我们将求和和乘法从for循环头中移出,则更容易阅读和理解。
for(int i = 0; i < 10; i++)
{
int value = rand() % 10;
sum += value;
product *= value;
std::cout << value << std::::endl;
}
接下来我们只想做if
乘以value
不等于0
。
for(int i = 0; i < 10; i++)
{
int value = rand() % 10;
sum += value;
if(value != 0)
{
product *= value;
}
std::cout << value << std::::endl;
}
所以整个程序看起来像这样。
#include <iostream>
#include <cstdlib>
#include <ctime>
int main()
{
std::cout << "draws 10 numbers:" << std::endl;
srand(time(0));
int sum = 0 ;
int product = 1;
for(int i = 0; i < 10; i++)
{
int value = rand() % 10;
sum += value;
if(value != 0)
{
product *= value;
}
std::cout << value << " ";
}
std::cout << std::endl;
std::cout << "the sum is " << sum << std::endl;
std::cout << "the product is " << product << std::endl;
return EXIT_SUCCESS;
}
此修改必须解决您的问题,您只需要在进行乘法之前检查value
是否不等于零。
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
cout << "draws 10 numbers:" << endl;
cout << endl;
srand(time(0));
int sum = 0 ;
int product=1;
for(int i=0,value=0;i<10;i++)
{
value = rand()%10;
sum+=value;
if(value != 0)
product*=value;
cout << value << endl;
}
cout<<"the sum is "<< sum <<endl;
cout <<"the product is "<< product <<endl;
return 0;
}
编辑:我的意思不是粗鲁,但我必须警告您,您不应在任何for循环的标题内编写代码,这是丑陋的,令人困惑的和意外的。您应该只在for循环内编写代码,好吗? :)否则,将来您或其他人可能看不到代码。