【问题标题】:Not getting the desired output. Can someone tell me the solution?没有得到想要的输出。有人可以告诉我解决方案吗?
【发布时间】:2015-11-14 12:02:59
【问题描述】:
#include<stdio.h>

int calsum(int x, int y, int z);

void main()
{
    int a,b,c,i, sum;
    for(i = 1; i <= 3; i++)
        printf("\n Enter Number %d\n", i);

    scanf("%d %d %d", &a, &b, &c);
    sum= calsum(a,b,c);
    printf("\nSum=%d", sum);
}

int calsum(int x, int y, int z)
{
    int d;
    d = x + y + z;
    return (d);
}

嗨,我想一一输入数字,但我得到的输出是..

amol@amol-HP-Pavilion-15-Notebook-PC ~/Desktop/C codes $ ./a.out

Enter Number 1

Enter Number 2

Enter Number 3

而我希望它一次要求我输入一个。请帮我。我是新手。

【问题讨论】:

  • 真正的问题更多的是接受输入而不是输出。

标签: c function


【解决方案1】:
  1. 你的for 循环里面只有一行代码,

    printf("\n Enter Number %d\n", i);
    

    所以输出是正确的。

  2. main() 必须返回 int

  3. 必须检查scanf()的返回值。
  4. 你可以使用这样的东西

    #include <stdio.h>
    
    int calsum(int x, int y, int z);
    int getinteger();
    
    int main()
    {
        int a, b, c, z;
    
        a = getinteger(1);
        b = getinteger(2);
        c = getinteger(3);
    
        z = calsum(a, b, c);
    
        printf("\nSum = %d", z);
    
        return 0;
    }
    
    int calsum(int x, int y, int z)
    {
        int d;
        d = x + y  +z;
        return d;
    }
    
    int getinteger(int index)
    {
        int value;
        printf("Enter the %dth number > ", index);
        while (scanf("%d", &value) != 1)
        {
            int chr;
            while (((chr = getchar()) != '\n') && (chr != EOF))
                continue;
            printf("Invalid input -- try again\n");
            printf("Enter the %dth number > ", index);
        }
        return value;
    }
    

【讨论】:

    【解决方案2】:

    您可以为此使用数组

    int a[3], i, sum;
    for (i = 0; i < 3 ; i++)
    {
        printf("\n Enter Number %d\n", i+1);
        scanf("%d", &a[i]);
    }
    sum = calsum(a[0], a[1], a[2]);
    

    【讨论】:

    • 剩下的代码呢?即我应该对其他功能进行哪些更改?
    • Paul Ogilvie,我应该在 calsum 函数中做什么?
    • 您能帮我解决需要对功能进行的更改吗? @哈里斯
    • @AmolSehgal 你的功能很好,你不需要做任何改变。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    相关资源
    最近更新 更多