任何人都可以告诉我这段代码中的问题在哪里? [英] can anyone please tell me where is the problem in this code ?

查看:69
本文介绍了任何人都可以告诉我这段代码中的问题在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从屏幕上扫描8个值,如1 2 3 4 5 6 7 8,我想打印这8个值的总和,并且必须使用数组...



i want to scan 8 values from screen like - 1 2 3 4 5 6 7 8 and i want to print the sum of those 8 values and have to use array ...

#include "stdafx.h"
#include <stdio.h>
#include <math.h>

#define MAX_ITEM 8

int main()
{
	double x[MAX_ITEM],
		sum;
		
	int i;
	printf("enter 8 number seprated by blank ");
	scanf_s("%lf", &x[0]);
	sum = 0;
	for (i = 0; i <= MAX_ITEM; i++);
	sum += x[i];

	printf("sum  = %lf \n", &sum);

推荐答案

我觉得删除分号(; )at 的结尾应该有效。

Hi, I feel removing semicolon (;) at the end of for should work.
for (i = 0; i <= MAX_ITEM; i++)
	sum += x[i];







谢谢

Hariharasudhan C




Thanks
Hariharasudhan C


问题是你只需要初始化数组中一个元素的值。您应该在循环内依次扫描每个值,确保在i等于MAX_ITEM时循环结束。您还需要在每个数字后刷新输入流,以清除行结束字符。所以你应该得到类似的东西:

The problem is that you only ever initialise the value of one element of your array. You should scan each value in turn inside your loop, ensuring that your loop ends when i is equal to MAX_ITEM. You also need to flush the input stream after each number, to clear the line end characters. So you should end up with something like:
int i;
sum = 0.0; // clear the sum
for (i = 0; i < MAX_ITEM; i++) // ensure loop ends after MAX_ITEM elements
{
    printf("enter a number: ");
    scanf_s("%lf", &x[i]);     // get next value
    fflush(stdin);             // clear the input buffer
    sum += x[i];               // add to the sum
}
printf("sum  = %lf \n", sum);



正如您所看到的,在这种情况下,数组x并不是必需的,因为它在读取值后从未使用过。单个变量可以完成这项工作。


As you can see the array x is not really necessary in this case as it is never used after reading a value. A single variable would do the job.


这篇关于任何人都可以告诉我这段代码中的问题在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆