龟速学习visualc++2

    技术2022-05-11  75

    今天起来之后想编写一个比较三个数字大小的程序,结果书写程序如下: [Copy to clipboard] CODE: // max_value.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> using namespace std; [color=red]void swap (double x, double y)[/color] {         //double x,y;         double temp;         temp=y;         y=x;         x=temp;         //return x,y; } void main(void) {         /*double x,y;         double first,second;         cin>>first>>second;     x=first;         y=second;         swap(x,y);         cout<<x<<y;*/         cout<<"请依次输入三个数字."<<"以下将按照从小到大的顺序排列/n";         double first,second,third;         cin>>first>>second>>third;         if(second>third) swap(second,third);         //cout<<second;         if(first>second) swap (first,second);         cout<<"这是经过排列的三个数字:/n";         cout<<first<<" "<<second<<" "<<third<<"/n";         //return 0;*/ } 结果自然是死活运行不出来的...怎么输入怎么输出,后来看了看书知道了错误的地方. 问题就出在swap函数这里. 正确的写法应该为:void swap (double& x, double& y) 让我们看看为什么应该这么写.以下为书本原语: 如果输入参数以值的方式传递对象,则宜改用"const &"方式来传递,这样可以省去临时对象的构造和析构过程,从而提高效率. 这样问题基本就是这样了.同时关于函数的参数传递,还有以下需要注意的: 1.参数书写要完整. 2.命名要合理. 3.如果参数是指针,且仅作输入用,则应该在类型前加const,以防止该指针在函数体内北任意修改.例如: void StringCopy(char *strDestination,const char *strSource); 4.如上我的问题. 5.避免函数有太多的参数,参数个数尽量控制在5个以内,参数过多容易搞混. 6.尽量不要使用类型和数目不确定的参数.C的标准库函数printf是采用不确定参数的典型代表,其原型为: int printf(const char *format[, argument]...); 这种风格的函数在编译时丧失了严格的类型安全检查. 以上就是今天的一点体会...  

    最新回复(0)