【编程札记】Problem 1143 - Part-time Job

来源:互联网 发布:如何用winhex数据恢复 编辑:程序博客网 时间:2024/05/16 05:14
Description
Snoopy lost his wallet, but he is afraid to tell his family, so he decided to do a part-time job to earn money in weekends. He is selling 
washing machines in a big market, he will get p dollars by sold a washing machine, and the manager promised him that snoopy will get 
at least m dollars a day, it means that if snoopy didn't sold as many washing machines to get m dollars, the manager will pay him m dollars also. 

Now we told you the p and m, and the number of washing machines snoopy sold in a day, which we call it n, help snoopy to calculate 
how many dollars he can get. 
Input
  There are multiple test cases in the input file. Each line is a test case, there is three integers m, p, and n which are descript in the problem.
  Input is terminated by p = n = m = 0. ( 1 <= p, n, m <= 100 )
Output
  For each test case, output an integer that the payment snoopy can get in a single line.
Sample Input
20 5 3
20 5 5
0 0 0
Sample Output
20
25
该题非常简单,但是我在Dev C++上调试却总是出问题
编码如下:
#include<stdio.h>
#include<stdlib.h>
int cal_pay(int m,int p,int n){
    int tmp;
    tmp=p*n;
    if(tmp>m) return tmp;
    else return m;
    }
int main(){
    int m[20],p[20],n[20];//由于事先无法得知参数有几组,所以就假设最大为20
    int i=0;
    do{
    scanf("%d %d %d",&m[i],&p[i],&n[i]);
    i++;
    }
    while((m[i-1]!=0)||(p[i-1]!=0)||(n[i-1]!=0));
    int salary[i];
   
    for(int j=0;j<i-1;j++){
                     salary[j]=cal_pay(m[j],p[j],n[j]);
                     printf("%d\n",salary[j]);
                     }
return 0;
                     system("pause");
                     
                   
    }
此题出处 http://acm.whu.edu.cn/learn/problem/detail?problem_id=1143
编译没问题,执行,输入数据,黑框一闪而过,不显示结果,纠结很久,但是代码算法本身好像没有什么问题,隐约感觉自己肯能在某些地方犯了一个
隐蔽的或是很低级的错误。慢慢找,最后终于,最后两行写反了!!! return 0;和system("pause");调换顺序后,执行成功。于是submit,可是系统却
给一个Runtime Error(Segment Fault),系统结识:段错误,通常是栈溢出、非法指针访问(如越界)。整个代码里唯一让我不安的地方就是数组的长
度,我很莽撞地定义为20,于是改正如下:
#include<stdio.h>
#include<stdlib.h>
int cal_pay(int m,int p,int n){
    int tmp;
    tmp=p*n;
    if(tmp>m) return tmp;
    else return m;
    }
int main(){
    int m,p,n;
    int i=0;
    int salary[100];
    do{
    scanf("%d %d %d",&m,&p,&n);
    salary[i]=cal_pay(m,p,n);
    i++;
    }
    while((m!=0)||(p!=0)||(n!=0)); 
    for(int j=0;j<i-1;j++){
                    
                     printf("%d\n",salary[j]);
                     }
                     system("pause");
                     return 0;
          
    }
m经改正m,p,n都作为局部变量,避免了过多使用数组(随意定义长度的数组不一定够用),submit之后,AC了。
真是想不到,本以为10几分钟的题目居然栽在了小细节当中,虽然这个道理大家都懂,但是当它以一种出乎意料的方式出现在
自己面前时,依然让人印象深刻。我记得《showstopper》里有这么一句话:编程就是,不完美,就是灾难。

原创粉丝点击