最大乘积问题
应用循环,数组, 求帮助。 #include <stdio.h>int main(void)
{
int c , d , i , n , s ;
scanf("%d" , & n) ;
for(c = i = 0 , s = 1 ; i < n ; i ++) {
scanf("%d" , & d) ;
if(d > 0) {
s *= d ;
c ++ ;
}
}
if(c > 1) printf("%d\n" , s) ;
else printf("-1\n") ;
}
编译、运行实况:
D:\\C>g++ -o x x.c
D:\\C>x
5
2 5 -1 2 -1
20
D:\\C> #include <stdio.h>
#include <math.h>
int main()
{
int max=-1, n, i,j,k, temp;
scanf("%d", &n);
int a;
for (i=0; i<n; i++)
scanf("%d", &a);
for (i=0; i<n; i++){//从0开始取子序列
for (j=1; j<=n-i; j++){//子序列的长度
temp = 1;//计算每组序列的乘积,与max比较取最大
for (k=0; k<j; k++){
temp *= a;
}
if (temp>max){
max = temp;
}
}
}
printf("%d", max);
return 0;
}
#include <stdio.h>
#define ll long long
int main()
{
int n;
scanf("%d", &n);
ll numbers;
ll qzj;
ll pos, neg;
int len1 = 0, len2 = 0;
for(int i=0; i<n; ++i) {
scanf("%lld", &numbers);
if(i == 0) qzj = numbers;
else qzj = qzj * numbers;
if(qzj > 0) pos = qzj;
else if(qzj < 0) neg = -qzj;
else break;
}
ll min_ = pos;
ll pos_max = pos;
for(int i=1; i<len1; ++i) {
ll temp = pos / min_;
pos_max = (temp > pos_max ? temp : pos_max);
min_ = (pos < min_ ? pos : min_);
}
min_ = neg;
ll neg_max = neg;
for(int i=1; i<len2; ++i) {
ll temp = neg / min_;
neg_max = (temp > neg_max ? temp : neg_max);
min_ = (neg < min_ ? pos : min_);
}
if(len1 == 1 && len2 == 1) printf("-1");
else printf("%lld", (pos_max > neg_max ? pos_max : neg_max));
return 0;
} 楼上正解~ 本帖最后由 zhangjinxuan 于 2022-11-3 19:17 编辑
因为大于零的数如果你选了,结果不会变差,只会变好,如果不选,他就不是最大乘积了,很基础的,一个循环,甚至不需要数组就可以搞定
#include <stdio.h>
int main() {
int n, cnt = 0, a;
unsigned long long res = 1;
scanf("%d", &n);
for (int i = 1; i <= n; ++i)
scanf("%d", &a);
for (int i = 1; i <= n; ++i) {
if (a >= 1) {
res *= a;
++cnt;
}
}
if (cnt) printf("%llu", res);
else printf("-1");
return 0;
} #include<stdio.h>
int _max(int a, int b)
{
return a > b ? a : b;
}
int a;
int f;
int main()
{
int n, i, j, s = 0;
scanf("%d", &n);
for(i = 0;i<n;i++)
{
scanf("%d",&a);
}
for(j = 1;j<n;j++)
{
f = a;f = f*a;
}
for(i = 1;i<n;i++)
{
f = 1;
for(j = i;j < i; j++)
{
f = f*a;
}
}
for(i = 0;i<n;i++)
{
for(j = i;j<n;j++)
{
s = _max(s,f);
}
}
if(s == 0)
{
printf("-1\n");
}
else
{
printf("%d\n",s);
}
return 0;
}
hamletroy 发表于 2022-11-3 19:36
#include
int _max(int a, int b)
我没理解题意吗?为什么这么做? 要开long long !因为10^18会爆int! jackz007 发表于 2022-11-2 23:47
编译、运行实况:
s 要开 long long !因为10^18会爆int!
页:
[1]