【问题标题】:Get the value from function array从函数数组中获取值
【发布时间】:2013-12-10 23:30:44
【问题描述】:

我在作业中有这个问题,如果有人可以提供帮助,我会很高兴:

编写一个程序将整数存储在大小为 10 的数组中,在函数 Get_value() 中初始化您的数组,用户将在其中输入 10 个整数来填充数组。该程序然后为用户打印下面给出的菜单,并且必须能够执行用户选择的各种功能..用户命令是: D 显示数组中所有非零值 T 显示总数 R以相反的顺序显示所有数字 Q 退出程序 在 C++ 中 我试着写,但我没有得到确切的答案

#include <stdio.h>
int get_value();
int display();
void total(void);
int main ()
 {
int get_value[10];  
int i;
char c=0;

for(i=0;i<=9;i++){
    printf("Enter The value of get_value[%d]\n",i);
    scanf("%d",get_value[i]);
}

printf(" D to display all non-zero values in the array \n choose T to display the  total \n choose R to display all the number in reverse order \n choose Q to quit the program \n");
scanf("%d",&c);

if(c == D){
        display();
}
else if(c== T){
    total();
}
   return 0;

   }
int display()
{
    int i,get_value[10];
    for(i=0;i<=9;i++){
        if(get_value[i]!=0)
            printf("%d",get_value[i]);
    }
    return 0;
}
void total(void)
{
    int i,sum=0;
    for(i=0;i<=9;i++){
        sum+=i;
    }
        printf("%d",sum);
}

【问题讨论】:

  • 你有什么问题?你的描述很模糊。此外,这非常类似于 C。你的total 函数基本上是std::accumulate。你的display 函数基本上是std::copy_if
  • 啊,您正在读取一个整数,然后将其与我所知道的应该是编译器错误的内容进行比较。你在某处有'D'和'T'#defined吗?
  • @robbmj,或者只是简单地声明。 #define 不是合适的工具。
  • 如何将值从 main 发送到定义并打印出来
  • @user3088939,将其作为参数传递。

标签: c++ arrays function parameter-passing


【解决方案1】:

注意:

if (c == D)

应该是:

if (c == 'D')

同样:

else if (c == T)

应该是:

else if (c == 'T')

还有其他各种问题,例如正如他已经指出的那样:

scanf("%d",&c);

不正确 - 应该是:

scanf("%c",&c);

虽然:

c = getchar();

可能更好。

【讨论】:

  • 执行 char c=0; scanf("%d",&c);工作? char 的地址,它寻找一个 int。我知道 chars 只是 int 以不同的方式解释。
  • @robbmj 很好。我不希望从输入中读取单个字符。
  • 谢谢 - 代码似乎有很多问题 - 我现在已将 scanf 问题添加到答案中。
【解决方案2】:
#include <stdio.h>

int get_value();
int display(int values[], int n);
void total(int values[], int n);

int main()
{
    int n;
    n = 10;
    int values[n];
    int i;

    for(i=0;i<=n;i++){
            printf("Enter The value of get_value[%d]\n",i);
        values[i] = get_value();
    }

    printf(" D to display all non-zero values in the array \n choose T to display the  total \n choose R to display all the number in reverse order \n choose Q to quit the program\n");


    char c;
    scanf(" %c", &c);

    if(c == 'D') {
            display(values, n);
    }
    else if(c == 'T') {
            total(values, n);
    }
    else if (c == 'R') {

    }
    return 0;
}

int get_value()
{
        int usersChoice;
    scanf("%d", &usersChoice);
    return usersChoice;
}

int display(int values[], int n)
{
    int i;
    for(i=0;i<=n;i++){
        if(values[i]!=0)
            printf("%d", values[i]);
    }
    return 0;
}

void total(int values[], int n)
{
    int i,sum=0;
    for(i=0;i<=n;i++){
        sum+=values[i];
    }
    printf("%d",sum);
}

我想这会回答你所有的问题。

【讨论】:

  • 它现在可以工作了..但输出错误..我如何发送定义的值?
猜你喜欢
  • 1970-01-01
  • 2021-03-22
  • 2019-03-25
  • 2021-06-07
  • 1970-01-01
  • 2014-04-21
  • 1970-01-01
  • 2014-03-30
相关资源
最近更新 更多