简体   繁体   English

C中N个自然数的总和

[英]Sum of N natural numbers in C

The exercise asks me to write a program that first prompts the user to type in a sequence of natural numbers and then displays the sum of all the numbers in the sequence entered, assuming that the sequence of numbers ends with the integer value -1 (this value must not be added to the final result) and that the sequence may be empty.练习要求我编写一个程序,首先提示用户输入自然数序列,然后显示输入序列中所有数字的总和,假设数字序列以整数值-1结尾(这value 不得添加到最终结果中)并且序列可能为空。 I'm supposed to use a while statement in the implementation.我应该在实现中使用while语句。

Execution examples (the line 3 4 5 6 -1 is the user input):执行示例(第3 4 5 6 -1是用户输入):

Type in a sequence of natural numbers that ends in -1: 
3 4 5 6 -1
The sum is: 
18 

Here's the code I have:这是我的代码:

#include <stdio.h>

int main(){
    int aux=0, aux_1=0;
    printf("Escriba una secuencia de numeros naturales que acabe en -1: ");
    while(aux != -1)
    {
        scanf("%d", &aux);
        aux_1 = aux_1 + aux;
    }
    printf("\nLa suma es: %d\n", aux_1);
}

I don't know how to solve it in a way that it doesn't add -1 in the final result我不知道如何以不会在最终结果中添加-1的方式解决它

Like this?像这样? If you first read, then check as the loop condition, then add and read again in the loop:如果您先阅读,然后检查循环条件,然后在循环中添加并再次阅读:

int main(){
    int aux=0, aux_1=0;
    printf("Escriba una secuencia de numeros naturales que acabe en -1: ");
    scanf("%d", &aux);
    while(aux != -1) {
        aux_1 = aux_1 + aux;
        scanf("%d", &aux);
    }
    printf("\nLa suma es: %d\n", aux_1);
}

This way the -1 will not be added at the end.这样 -1 将不会添加到最后。

EDIT: to answer your question in the comments.编辑:在评论中回答您的问题。

#include <stdio.h>

int main(){
    int aux=0, aux_1=0;
    printf("Escriba una secuencia de numeros naturales que acabe en -1: ");
    do {
        scanf("%d", &aux);
        if (aux != -1) aux_1 += aux;
    }
    while(aux != -1);
    printf("\nLa suma es: %d\n", aux_1);
}
#include <stdio.h>
#include <conio.h>

void main(){
    int n, sum=0;
    printf("Enter the sequence of numbers");
    while(n){
        scanf("%d", &n);
        if (n == -1){
         break;
         }
        else
        sum = sum+n;
        
    }
    printf("\n the sum is %d\n", sum);
}
#include <stdio.h>

int main(){
    int aux=0, aux_1=0;
    printf("Escriba una secuencia de numeros naturales que acabe en -1: ");
    while(1){
        scanf("%d", &aux);
        if (aux == -1){
         break;
         }
        else
        aux_1 += aux;
    }
    printf("\nLa suma es: %d\n", aux_1);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM