极客工坊

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 10693|回复: 2

大家帮忙分析下这段代码

[复制链接]
发表于 2015-5-4 17:59:32 | 显示全部楼层 |阅读模式
看书发现有一段代码怎么实践都不通过
麻烦大家帮忙分析一下。
  1. #include <stdio.h>
  2. #define READINGSPERDAY 24
  3. #define VERYHIGHTEMPERATURE 200
  4. #define VERYLOWTEMPERATURE -200
  5. int todaysReadings[]={62,64,65,68,70,70,71,72,74,75,78,79,79,78,73,70,69,68,64,63,61,59 };
  6. void setup(){
  7.         Serial.begin(9600);
  8. }
  9. void loop(){
  10.         int lowTemp;
  11.         int hiTemp;
  12.         int retVal;

  13.         retVal = CalculateMinMax(todaysReadings, &lowTemp, &hiTemp);
  14.         Serial.println("=== Sfter the function call :");
  15.         Serial.print("The lvalue for lowTemp is :");
  16.         Serial.print((long) &lowTemp,DEC);
  17.         Serial.print("and the rvalue is :");
  18.         Serial.println((long) lowTemp,DEC);
  19.         Serial.print("The lvalue for hiTemp is:");
  20.         Serial.print((long) &hiTemp,DEC);
  21.         Serial.print(" and the rvalue is: ");
  22.         Serial.println((long) hiTemp,DEC);
  23.         Serial.println("\n");
  24.        
  25.         Serial.flush();
  26.         exit(0);

  27. }
  28. int CalculateMinMax( int temps[],int *minTemp, int *maxTemp){
  29.         int j;
  30.         *minTemp = VERYHIGHTEMPERATURE;
  31.         *maxTemp = -VERYLOWTEMPERATURE;
  32.         for (j = 0; j <READINGSPERDAY; j++ ){
  33.                 if(temps[j] >= *maxTemp){
  34.                         *maxTemp = temps[j];
  35.                 }
  36.                 if(temps[j] <= *minTemp){
  37.                         *minTemp = temps[j];
  38.                 }               
  39.         }
  40.         return j;
  41. }
复制代码


输出如下,能计算出最低气温,但是计算不出最高气温,不理解开始定义VERYLOWTEMPERATURE -200,函数内部为什么又定义一次*maxTemp = -VERYLOWTEMPERATURE; 这样数值就为正了吧?
for循环中判断的函数temps[j] >= *maxTemp   假如为69  >=  -200?


  1. === Sfter the function call :
  2. The lvalue for lowTemp is :2296and the rvalue is :61
  3. The lvalue for hiTemp is:2294 and the rvalue is: 24941
复制代码

回复

使用道具 举报

发表于 2015-5-4 21:53:53 | 显示全部楼层
(1)Line 33 错了,
   应该  *maxTemp = VERYLOWTEMPERATURE;

(2)你的 Line 2 这样
   #define READINGSPERDAY 24
可是其实 Line 5 的 todaysReadings[] 只有 22 个数据
这样会多比较两项 "乱七八糟" 的未知数,
有可能导致答案不正确 !
回复 支持 反对

使用道具 举报

 楼主| 发表于 2015-5-5 08:59:37 | 显示全部楼层
本帖最后由 li23108 于 2015-5-5 09:02 编辑
tsaiwn 发表于 2015-5-4 21:53
(1)Line 33 错了,
   应该  *maxTemp = VERYLOWTEMPERATURE;


谢谢你朋友 ,确实是数组内数据不完整造成的。

  1. === Sfter the function call :
  2. The lvalue for lowTemp is :2296 and the rvalue is :59
  3. The lvalue for hiTemp is:2294 and the rvalue is: 80

复制代码


*temps[23]   *temps[24]  地址的数据是不确定的大! 所以 以不确定的大进行比较 所以输出的值就是不确定的大
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

Archiver|联系我们|极客工坊

GMT+8, 2026-6-16 23:39 , Processed in 0.094343 second(s), 18 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表