如何在不使用数组、指针或结构的情况下 return 多个值?

How can I return multiple values without using arrays or pointers or structures?

我们得到了将十进制转换为二进制的源代码,octal.This 是我将使用函数 Dec2BinOct() 来 return 转换后的十进制值的源代码。

#include<stdio.h>
int main()
{
    unsigned long n, place=1, bin=0, r, o=0, place2=place;  
    printf("Conversion: Decimal to binary and octal.\n");
    printf("Enter number: ");
    scanf("%lu", &n);
    printf("%lu is ", n);
           
    for(unsigned long g = n; g != 0; place = place * 10)  {  
        r = g % 2;    
        bin = bin + (r * place);
        g = g / 2;  
    }  
    
    printf("%lu in Binary Form. \n", bin);
                
    printf("%lu is ", n);
    while (n != 0) {
        o = o + (n % 8) * place2;
        n =   n / 8;
        place2 = place2 * 10;
    }
    printf("%lu in Octal Form.\n\n", o);
    return 0;
}

我们的任务是为我们的作业应用函数,并且被要求使用函数 Dec2BinOct() ,如前所述,但我们的老师告诉我们这是最低要求的函数。经过这么多次尝试,我似乎没有得到正确的程序。我只是需要一些帮助,这是明天到期的。感谢您的所有帮助

如果您想要多个值而不是一次,您可以只概括这两个操作并提供数字应转换为的基数:

unsigned long Dec2AnotherBase(unsigned long n, int base){
    unsigned long place=1, result=0;
    for(; n; place*=10, n/=base) 
        result += n % base * place;
    return result;
}

在您的主要功能中,您将循环替换为:

bin=Dec2AnotherBase(n, 2);
o=Dec2AnotherBase(n, 8);

我还稍微简化了您的代码。这是我所做的:

  • bin=bin+(r*place)place=place*10 替换为较短的 bin+=r*placeplace*=10
  • 消除了 r 变量,因为它只使用了一次(也不需要 % 周围的括号,因为 % 运算符与 * 具有相同的优先级并且评估为左-向右)。
  • 使用 , 运算符在增量语句中移动了 g=g/2
  • 删除了循环中不再需要的花括号,简化为单个语句。
  • 删除了g,因为它是不必要的创建(您可以直接在n上操作,因为它已经是传递给函数的变量的副本)。
  • 有争议: 将条件中的 n!=0 替换为 n,因为每个非零值都隐式转换为逻辑真值。