c-添加数组元素的结果错误


#include<stdio.h>
int main()
{ 
int get()
{
int n;
int sum=0;
int  i;
int a[i];
printf("enter the value of n");
scanf("%d",&n);
if(n==5)
{
printf("ok");
}
else
{
printf("not ok dont enter next value re run the program");
}
printf("enter the values of array");
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
printf("the sum of array is ");
for(int i=1;i<=n;i++)
{
sum=sum+a[i];
printf("%dn",sum);
}
}
get(); 
return 0;  
}

但当我在下面写代码时,它并没有像我期望的那样给出输出

#include<stdio.h>
int main()
{ 
int get()
{
int n;
int sum=0;
int  i;
int a[i];
printf("enter the value of n");
scanf("%d",&n);
if(n==5)
{
printf("ok");
}
else
{
printf("not ok dont enter next value re run the program");
}
printf("enter the values of array");
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
printf("enter the values of array");
for(int i=1;i<=n;i++)
{
printf("%d",a[i]);
}
printf("the sum of array is ");
for(int i=1;i<=n;i++)
{
sum=sum+a[i];
printf("%dn",sum);
}
}
get(); 
return 0;  
}

它没有给出预期的输出,请帮助

问题

您得到一个由N个整数组成的数组A。

任务

打印数组中元素的总和。

注意:有些整数可能相当大。

输入格式

第一行包含表示数组大小的单个整数N
下一行包含用空格分隔的整数,表示数组的元素。

输出格式

打印表示数组中元素总和的单个值。

限制

1<N<10

0<a[i]<10^10

样本输入

5
1000000001 1000000002 1000000003 1000000004 1000000005

样本输出

500000015

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long int list;

int main() {
/* Enter your code here. Read input from STDIN. Print output to 
STDOUT */   
list n,sum=0;
cin>>n;
while(n--)
{
list a;
cin>>a;
sum+=a;
}
cout<<sum;
return 0;
}

这个程序给出了正确的解决方案。理解起来相当复杂,但它能按照预期工作

#include <stdio.h>
int main() 
{  
int i, n, value;
long long sum = 0;
scanf("%d", &n);
for (i = 0; i < n; i++)
{
scanf("%d",&value);
sum =sum + value;
}
printf("%lld", sum);
return 0;
}

这个c程序被机器接受,这是一个简单得多的形式,除了变量值如何在没有[]这些符号的情况下充当数组

您的代码中存在多个问题:

  • 由于演示文稿不好,阅读起来非常困难。您应该一致地使用缩进,4个字符被认为是优选的。

  • 不能在标准C中定义本地函数。在main()函数之前定义get(),或者直接在main()函数内部编写代码。

  • 定义具有未初始化的CCD_ 5的阵列CCD_。在读取元素数n之后,您可以将数组定义为int a[n];,但实际上不需要数组:您可以在读取值时计算总和。

  • 如果总和超过INT_MAX,则应为sum使用类型long long以帮助避免溢出。

  • 更复杂的程序是用C++编写的,C++是一种不同的语言,最初受到C语言的启发,但今天却大不相同。该代码通过非常令人困惑的listtypedef使用类型long longwhile(n--)是有风险的:如果用户输入负值,并且没有对无效输入进行错误处理,则循环将继续读取值。

这是一个修改后的版本:

#include <stdio.h>
int main() {  
int i, n, value;
long long sum = 0;
printf("enter the value of n: ");
if (scanf("%d", &n) != 1) {
printf("invalid input, re run the programn");
return 1;
}
printf("enter the values of array: ");
for (i = 0; i < n; i++) {
if (scanf("%d", &value) != 1) {
printf("invalid input, breaking from the loopn");
break;
}
sum += value;
}
printf("the sum of array is %lldn", sum);
return 0;  
}

最新更新