为什么此代码不起作用? [关闭]

问题描述 投票:-5回答:3

这是C语言,我使用的是Dev-C ++(但保存在c扩展中),并使用Dev-C ++的编译器进行编译。编译日志中未显示任何错误或警告。该程序是一个“数组” ,“用于”,“做一会儿”练习。

对任何短语错误,抱歉,我的母语不是英语,这是我在本网站上遇到的第一个问题...如果您需要更多信息,请询问(但我可能不会很快回答)。

#include <stdio.h>
#include <stdlib.h>
main(){
    int num[10];
    int cont=0;  
    for (cont=0;cont==9;cont++){
        num[cont]=(cont+1)*3;
        }
    printf("\nThis programs show the multiplication table of the number 3\n Digit the number you want \n To exit input -9... \n");
    do{
       cont=0;
       scanf("%d",&cont);
       if (cont>10 || cont<1){
            if(cont!= -9){
                printf("You digitted a not valid number");
            }
        }
        printf("The number 3 multiplied by %d is equal to: %d \n\n",cont,num[cont-1]);
    }while(cont!=(-9));
    getch();
}

ps:请不要太复杂的答案,我是非常非常新手。再次为我的语言错误感到抱歉。

c
3个回答
2
投票
for (cont=0;cont==9;cont++){

for循环的第二部分是继续条件,而不是结束条件。基本上,循环继续,而第二部分为true。

因此,由于cont从0开始,并且仅在cont == 9 ...时才继续运行,它实际上从未运行。尝试改用cont <= 9,当它小于或等于9时它就会消失。


2
投票

看来您的问题出在这行代码:

for (cont=0;cont==9;cont++){

for()的语法为:for(starting_with; while_true; do_each_loop)因此,当您说cont==9时,意味着循环仅在cont等于9时运行。您可能想要类似cont <= 9的内容。


0
投票

一些问题

  1. for循环的测试和极限是错误的。

    int num[10];
    for (cont=0; cont<10; cont++) {
    
    // or even better
    #define N 10
    int num[N];
    for (cont=0; cont<N; cont++) {
    ... 
      if (cont> N || cont<1){
    
  2. 代码使用无效索引访问数组,添加else

    if (cont>10 || cont<1) {
      if(cont!= -9){
        printf("You digitted a not valid number");
      }
    }
    else { 
      printf("The number 3 multiplied by %d is equal to: %d \n\n",cont,num[cont-1]);
    }
    
  3. 代码应检查scanf()的返回值。

    if (scanf("%d",&cont) != 1) break;
    
  4. 未成年人:非便携式main()签名

    // main(){
    int main(void) {
    
© www.soinside.com 2019 - 2024. All rights reserved.